Saturday, May 3, 2025

JavaScript Tutorial for Beginners

 

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

html
Copy
Download
Run
<!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

javascript
Copy
Download
let age = 25;          // Can be reassigned
const PI = 3.14;       // Cannot be reassigned
var oldWay = "Avoid";   // Old syntax (avoid in modern JS)

Data Types

TypeExample
Number423.14
String"Hello"'JS'
Booleantruefalse
Array[1, 2, 3]
Object{ name: "Alice" }
Nullnull
Undefinedundefined

2. Operators

Arithmetic Operators

javascript
Copy
Download
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

javascript
Copy
Download
5 == "5"    // true (loose equality)
5 === "5"   // false (strict equality)
10 > 5      // true
10 <= 10    // true

Logical Operators

javascript
Copy
Download
true && false   // false (AND)
true || false   // true (OR)
!true           // false (NOT)

3. Control Flow

If-Else Statements

javascript
Copy
Download
let age = 18;

if (age >= 18) {
    console.log("Adult");
} else {
    console.log("Minor");
}

Switch Statement

javascript
Copy
Download
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

javascript
Copy
Download
for (let i = 0; i < 5; i++) {
    console.log(i); // 0, 1, 2, 3, 4
}

While Loop

javascript
Copy
Download
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

javascript
Copy
Download
function greet(name) {
    return "Hello, " + name + "!";
}

console.log(greet("Alice")); // "Hello, Alice!"

Arrow Function (Modern JS)

javascript
Copy
Download
const greet = (name) => `Hello, ${name}!`;
console.log(greet("Bob")); // "Hello, Bob!"

5. Arrays & Objects

Arrays (Lists)

javascript
Copy
Download
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)

javascript
Copy
Download
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

javascript
Copy
Download
let heading = document.getElementById("title");
let buttons = document.querySelectorAll(".btn");

Changing Content

javascript
Copy
Download
heading.textContent = "New Title";
heading.style.color = "blue";

Event Listeners (Click, Hover, etc.)

javascript
Copy
Download
let button = document.querySelector("#myButton");
button.addEventListener("click", () => {
    alert("Button clicked!");
});

7. Async JavaScript (Promises, Fetch API)

Fetching Data from an API

javascript
Copy
Download
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)

javascript
Copy
Download
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