JavaScript Tutorial for Beginners
Introduction to JavaScript
JavaScript is a programming language that adds interactivity to websites. It runs in the browser and allows you to:
Modify HTML & CSS dynamically
Handle user events (clicks, inputs)
Fetch data from servers (APIs)
Create animations and games
Basic JavaScript Example
<!DOCTYPE html> <html> <head> <title>JavaScript Demo</title> </head> <body> <button onclick="alert('Hello!')">Click Me</button> <script> console.log("This runs when the page loads"); </script> </body> </html>
1. Variables & Data Types
Variables store data. JavaScript has dynamic typing (no need to declare types).
Declaring Variables
let age = 25; // Can be reassigned const PI = 3.14; // Cannot be reassigned var oldWay = "Avoid"; // Old syntax (avoid in modern JS)
Data Types
| Type | Example |
|---|---|
Number | 42, 3.14 |
String | "Hello", 'JS' |
Boolean | true, false |
Array | [1, 2, 3] |
Object | { name: "Alice" } |
Null | null |
Undefined | undefined |
2. Operators
Arithmetic Operators
let x = 10 + 5; // 15 (Addition) let y = 10 - 5; // 5 (Subtraction) let z = 10 * 2; // 20 (Multiplication) let w = 10 / 2; // 5 (Division) let mod = 10 % 3; // 1 (Modulus/Remainder)
Comparison Operators
5 == "5" // true (loose equality) 5 === "5" // false (strict equality) 10 > 5 // true 10 <= 10 // true
Logical Operators
true && false // false (AND) true || false // true (OR) !true // false (NOT)
3. Control Flow
If-Else Statements
let age = 18; if (age >= 18) { console.log("Adult"); } else { console.log("Minor"); }
Switch Statement
let day = "Monday"; switch (day) { case "Monday": console.log("Start of the week"); break; case "Friday": console.log("Weekend soon!"); break; default: console.log("Another day"); }
Loops
For Loop
for (let i = 0; i < 5; i++) { console.log(i); // 0, 1, 2, 3, 4 }
While Loop
let i = 0; while (i < 5) { console.log(i); // 0, 1, 2, 3, 4 i++; }
4. Functions
Functions are reusable blocks of code.
Basic Function
function greet(name) { return "Hello, " + name + "!"; } console.log(greet("Alice")); // "Hello, Alice!"
Arrow Function (Modern JS)
const greet = (name) => `Hello, ${name}!`; console.log(greet("Bob")); // "Hello, Bob!"
5. Arrays & Objects
Arrays (Lists)
let fruits = ["Apple", "Banana", "Orange"]; fruits.push("Mango"); // Add to end fruits.pop(); // Remove last element console.log(fruits[0]); // "Apple"
Objects (Key-Value Pairs)
let person = { name: "Alice", age: 25, isStudent: true }; console.log(person.name); // "Alice" person.age = 26; // Update property
6. DOM Manipulation (Changing HTML)
JavaScript can interact with HTML elements.
Selecting Elements
let heading = document.getElementById("title"); let buttons = document.querySelectorAll(".btn");
Changing Content
heading.textContent = "New Title"; heading.style.color = "blue";
Event Listeners (Click, Hover, etc.)
let button = document.querySelector("#myButton"); button.addEventListener("click", () => { alert("Button clicked!"); });
7. Async JavaScript (Promises, Fetch API)
Fetching Data from an API
fetch("https://api.example.com/data") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error("Error:", error));
Async/Await (Modern Way)
async function fetchData() { try { let response = await fetch("https://api.example.com/data"); let data = await response.json(); console.log(data); } catch (error) { console.error("Error:", error); } } fetchData();
No comments:
Post a Comment