What is Lexical Scope?

Lexical Scope means a function can access variables from its own scope and parent scope based on where the function is defined in the code.

const name = "Somnath";
function greet() {
console.log(name);
}
greet();

When JavaScript looks for name, it checks: It finds name in the global scope inside greet() and then parent (global) scope. This is lexical scope.


What is Closure ?

A closure is a function that has access to variables from its outer (lexical) scope even after the outer function has returned.

function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const increment = outer();
increment(); // 1
increment(); // 2
increment(); // 3
// outer() creates count.
// outer() returns inner().
// Normally, count would disappear when outer() finishes.
// But inner() keeps a reference to count.
// So count is remembered between calls.
// This "remembering" is called a closure.


How JavaScript Inheritance Works ?

Inheritance means one object can use properties and methods of another object.

JavaScript uses Prototype-based Inheritance

Object Prototype (__proto__)

Every object has an internal link to another object called its prototype.

const animal = {
eat() {
console.log("Eating...");
}
};
const dog = {
name: "Tommy"
};
Object.setPrototypeOf(dog, animal);
console.log(dog.name); // Tommy
dog.eat(); // Eating...

Function Prototype (prototype)

Every function automatically gets a prototype property.

function Animal() {}
console.log(Animal.prototype);

What is Prototype Chain?

A Prototype Chain is the mechanism JavaScript uses to find a property or method when it is not found directly on an object.

const animal = {
eat() {
console.log("Eating...");
}
};
const dog = {
name: "Tommy"
};
Object.setPrototypeOf(dog, animal);
dog.eat();

Leave a comment

Quote of the week

"People ask me what I do in the winter when there's no baseball. I'll tell you what I do. I stare out the window and wait for spring."

~ Rogers Hornsby