Category: Examples

  • Spread & Rest Operators

    let arr1 = [1, 2, 3];
    let arr2 = [...arr1, 4, 5]; // Spread
    console.log(arr2); // [1, 2, 3, 4, 5]
    
    function sum(...nums) { // Rest
      return nums.reduce((a, b) => a + b, 0);
    }
    console.log(sum(5, 10, 15)); // 30
    

    Explanation:

    • ... (spread) copies values.
    • ... (rest) collects multiple arguments.
  • Array Methods

    let numbers = [10, 20, 30, 40];
    
    console.log(numbers.map(n => n * 2)); // [20, 40, 60, 80]
    console.log(numbers.filter(n => n > 20)); // [30, 40]
    console.log(numbers.reduce((a, b) => a + b, 0)); // 100
    

    Explanation:

    • map() → transforms values.
    • filter() → selects values that match condition.
    • reduce() → accumulates into one value.
  • Switch Statement

    let day = 3;
    
    switch (day) {
      case 1: console.log("Monday"); break;
      case 2: console.log("Tuesday"); break;
      case 3: console.log("Wednesday"); break;
      default: console.log("Invalid day");
    }
    

    Explanation:

    • switch is used instead of multiple if-else.
    • Since day = 3, output → Wednesday.
  • While Loop

    let count = 1;
    while (count <= 5) {
      console.log("Count: " + count);
      count++;
    }
    

    Explanation:

    • while runs as long as the condition is true.
    • Prints Count: 1 to Count: 5.

  • DOM Manipulation

    HTML

    <p id="text">Hello!</p>
    <button onclick="changeText()">Change Text</button>
    

    JavaScript

    function changeText() {
      document.getElementById("text").innerHTML = "Text Changed!";
    }
    

    Explanation:

    • document.getElementById("text") selects the <p> element.
    • .innerHTML changes its cotent.
  • ES6 Arrow Functions

    const add = (a, b) => a + b;
    
    console.log(add(5, 3)); // 8
    

    Explanation:

    • Arrow functions are a shorter way to write functions.
    • add(5,3) returns 8.
  • Event Handling

    HTML

    <button onclick="sayHello()">Click Me</button>
    

    JavaScript

    function sayHello() {
      alert("Hello! You clicked the button.");
    }
    

    Explanation:

    • onclick calls the sayHello() function.
    • alert() shows a popup message.
  • Objects

    let person = {
      name: "Ali",
      age: 22,
      city: "Lahore"
    };
    
    console.log(person.name); // Ali
    console.log(person["city"]); // Lahore
    

    Explanation:

    • Objects store data in key-value pairs.
    • You can access using . or [""].
  • Arrays

    let fruits = ["Apple", "Banana", "Mango"];
    
    console.log(fruits[0]); // Apple
    console.log(fruits.length); // 3
    

    Explanation:

    • Arrays store multiple values.
    • fruits[0] → first item, fruits.length → total items.
  • For Loop

    for (let i = 1; i <= 5; i++) {
      console.log("Number: " + i);
    }
    

    Explanation:

    • for loop repeats code.
    • Here it prints numbers 1 to 5.