Important thoughts on JavaScript

__e19a78719dbdd7bc958

Takuro Goto

Posted on November 16, 2024

Important thoughts on JavaScript

1.Closures
A closure occurs when a function retains access to variables from its outer (enclosing) scope, even after the outer function has finished executing. This means that even though the outer function has returned, its local variables are still accessible by the inner function.

function counter() {
    let count = 0;
    return function() {
        return ++count;
    };
}

const increment = counter();
console.log(increment()); // 1
console.log(increment()); // 2
Enter fullscreen mode Exit fullscreen mode

the outter function is counter()
the inner function is return function() in the outter function
So a closure let the inner function access to the count variable in the outter function's scope even after the outert funcion has done with execution.

2.Prototypes
In JavaScript, prototypes allow you to share functions across multiple instances of an object. Instead of defining the same function in each instance, you can define it once on the object's prototype. This way, all instances of the object can access the same function, reducing redundancy and improving efficiency by saving memory and resources in your code.

// Constructor function (similar to a class in other languages)
function Person(name, age) {
    this.name = name;
    this.age = age;
}

// Adding a method to the `Person` prototype
Person.prototype.greet = function() {
    return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
};

// Creating new instances
const person1 = new Person('Alice', 30);
const person2 = new Person('Bob', 25);

// Calling the method on the instances
console.log(person1.greet()); // "Hello, my name is Alice and I am 30 years old."
console.log(person2.greet()); // "Hello, my name is Bob and I am 25 years old."
Enter fullscreen mode Exit fullscreen mode

Person1 and Person2 can access the greet function even though they don't have the greet function defined on their own.

đź’– đź’Ş đź™… đźš©
__e19a78719dbdd7bc958
Takuro Goto

Posted on November 16, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related