task 2
Wed Apr 23 2025 01:40:21 GMT+0000 (Coordinated Universal Time)
Saved by @cciot
1. Prototypal Inheritance and Classes
a. Prototypal Inheritance (old way):
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function () {
console.log(`${this.name} makes a sound.`);
};
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function () {
console.log(`${this.name} barks.`);
};
const dog = new Dog("Buddy", "Golden Retriever");
dog.speak(); // Buddy barks.
b. ES6 Classes (modern way):
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
console.log(`${this.name} barks.`);
}
}
const dog2 = new Dog("Max", "Labrador");
dog2.speak(); // Max barks.
2. Object and Array Destructuring
// Object destructuring
const user = {
id: 1,
name: "Alice",
contact: {
email: "alice@example.com",
phone: "123-4567"
}
};
const { name, contact: { email } } = user;
console.log(name); // Alice
console.log(email); // alice@example.com
// Array destructuring
const fruits = ["apple", "banana", "cherry"];
const [firstFruit, , thirdFruit] = fruits;
console.log(firstFruit); // apple
console.log(thirdFruit); // cherry
3. Working with Modules
a. Exporting from a module (file: mathUtils.js)
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
b. Importing in another file
import { add, subtract } from './mathUtils.js';
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
> ⚠️ Note: You need to run this in a module-supporting environment (e.g., browser with type="module" or Node with .mjs or appropriate config).
4. Function Generators and Symbols
a. Generator Function
function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}
const gen = numberGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
b. Symbols
const ID = Symbol("id");
const person = {
name: "Bob",
[ID]: 1234
};
console.log(person); // { name: 'Bob', [Symbol(id)]: 1234 }
console.log(person[ID]); // 1234
5. Working with Closures
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
};
}
const closureExample = outerFunction("outside");
closureExample("inside"); // Outer: outside, Inner: inside



Comments