JavaScript Essentials with Examples

// πŸ“Œ 1. Array Destructuring Example
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;

console.log("First number:", first); // 1
console.log("Second number:", second); // 2
console.log("Remaining numbers:", rest); // [3, 4, 5]

// πŸ“Œ 2. Using Rest Operator in Function
function sum(...num) {
    return num.reduce((acc, n) => acc + n, 0);
}

console.log("Sum of numbers:", sum(1, 2, 3, 5)); // 11

// πŸ“Œ 3. Constructor Function Example
function Person(name, age) {
    this.name = name;
    this.age = age;
    this.greet = function () {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    };
    this.isAdult = function () {
        console.log(this.age > 18 ? "Adult" : "Child");
    };
}

const person1 = new Person('John', 10);
console.log("Person Name:", person1.name);
person1.greet();
person1.isAdult();

// πŸ“Œ 4. Class Example
class Persons {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    greet() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
}

const alice = new Persons('Alice', 18);
alice.greet();
console.log("Alice's Age:", alice.age);

// πŸ“Œ 5. Object Example with Methods
const car = {
    name: 'XYZ',
    brand: 'ABC',
    year: 2002,
    display() {
        console.log("Car Brand:", this.brand);
    }
};

car.display();
console.log("Car Name:", car.name);

// πŸ“Œ 6. Nested Objects Example
const obj = {
    obj1: { name: 'Shamim', age: 25, place: "Delhi" },
    obj2: { name: 'Akhter', age: 23, place: "Patna" },
    obj3: { name: 'XYZ', age: 18, place: 'Noida' }
};

console.log("First Object Name:", obj.obj1.name);

// Filtering objects with age > 20
console.log("People with age greater than 20:");
for (const key in obj) {
    if (obj[key].age > 20) {
        console.log(obj[key].name);
    }
}

// Adding a new key-value pair to all objects
for (const key in obj) {
    obj[key].dob = '2992';
}
console.log("Updated Object with DOB:", obj);

// πŸ“Œ 7. Array of Objects Example
const people = [
    { name: "Shamim", age: 25, place: "Delhi" },
    { name: "Akhter", age: 23, place: "Patna" },
    { name: "XYZ", age: 18, place: "Noida" }
];

// Filtering people older than 20
const olderThan20 = people.filter(p => p.age > 20);
console.log("People older than 20:", olderThan20);

// Adding a new key "dob" to all objects
people.forEach(p => {
    p.dob = "01-01-2000";
});
console.log("Updated People with DOB:", people);

// πŸ“Œ 8. Using Map to Modify Data and Create a New Array
const updatedPeople = people.map(p => ({ ...p, country: "India" }));
console.log("People with country added:", updatedPeople);

// πŸ“Œ 9. Using Reduce to Calculate Sum of Ages
const totalAge = people.reduce((acc, p) => acc + p.age, 0);
console.log("Total Age of People:", totalAge);

// πŸ“Œ 10. Using Some and Every
const hasMinor = people.some(p => p.age < 18); // Checks if at least one person is a minor
console.log("Is there a minor?", hasMinor);

const allAdults = people.every(p => p.age >= 18); // Checks if all are adults
console.log("Are all adults?", allAdults);

// πŸ“Œ 11. Sorting an Array of Objects by Age
const sortedByAge = [...people].sort((a, b) => a.age - b.age);
console.log("People sorted by age:", sortedByAge);

πŸ”₯ Quick Overview Notes:
forEach β†’ Used when modifying the original array (e.g., adding a new key).
map β†’ Creates a new array with modified data (useful when you don’t want to modify the original).
filter β†’ Returns a new array with only elements that match a condition.
reduce β†’ Used for calculations like summing values from an array.
some β†’ Returns true if at least one element matches a condition.
every β†’ Returns true if all elements match a condition.
sort β†’ Sorts an array based on a condition (modifies original).