1=> ⚡️ Spread Operator(...)
let numbers = [1, 2, 3, 4]; let newArray = [...numbers, 5, 6]; console.log(newArray)
Output: [1,2,3,4,5,6]
2=> ⚡️ Closures in javascript with real world example
Closures: a function that returns another function with access to the parent scope. Example below:
function outerFunction(outerValue) { return function innerFunction(innerValue) { console.log(`Outer value: ${outerValue}, Inner value: ${innerValue}`); }; } const innerFunc = outerFunction("Hello"); innerFunc("World");
Output: "Outer value: Hello, Inner value: World"
Here we can see that parent function's variables are preserved and still accessible by child function even though parent function has been already executed.
Now, let's see a real world use case:
function createCounter() {
let count = 0;
function increment() {
count++;
console.log(`Count: ${count}`);
}
function decrement() {
count--;
console.log(`Count: ${count}`);
}
return {
increment,
decrement,
};
}
const counter = createCounter();
counter.increment(); // Output: "Count: 1"
counter.increment(); // Output: "Count: 2"
counter.decrement(); // Output: "Count: 1"
In this example, the createCounter function returns an object with two methods, increment and decrement. The count variable is defined inside the createCounter function and is not accessible outside of it. The increment and decrement methods have access to the count variable due to the closure created by the createCounter function.
This allows us to create an object with private variables and methods that are not accessible from outside the object, providing a way to encapsulate functionality and prevent outside code from interfering with the object's state.
3=> ⚡️ Prototypes in javascript with example
Prototypes: an object that is associated with every function and object in JavaScript. Example:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const john = new Person("John", 30);
const jane = new Person("Jane", 25);
john.greet(); // Output: "Hello, my name is John"
jane.greet(); // Output: "Hello, my name is Jane"
In this example, we define a Person constructor function that takes a name and an age parameter and sets them as properties on the newly created Person object using this. We then define a greet method on the Person.prototype object, which is shared by all Person objects.
By using the prototype object to define methods on the Person class, we can create new Person objects that inherit these methods, without having to define them again for each new object. This makes our code more efficient and easier to maintain, as we can make changes to the Person class and have those changes reflected in all instances of the class.
In addition, we can also use prototypes to add new methods and properties to existing objects, allowing us to extend their functionality dynamically.
Top comments (0)