DEV Community

Cover image for Summarizing Namaste 🙏 JavaScript EP09,10,11,12,13(Block scope and Closures)
Abhinav Singh Jamwal
Abhinav Singh Jamwal

Posted on

Summarizing Namaste 🙏 JavaScript EP09,10,11,12,13(Block scope and Closures)

Thank you Akshay Saini for this beautiful series. Just summarizing your lessons for whenever I need a quick recap. Same for others. Hope it helps.

What is block in Js?

A block is used to combine multiple statements together.
Example--> If there is one statement,
if(true) console.log('true');
If you want multiple statements, then you need a block.
if(true){
const a = 5;
const b = 6;
console.log(a+b);
}
Also known as Compound statements

What is block scope?

When a variable is only accessible in its block scope.
Example-->
if(true){
let a = 21;
const b = 212;
var c = 8;
}
a and b are block scoped which means you can't access them outside this block.
let and const are block scoped whereas var is not.

Closure

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain.

The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets),
it has access to the outer function’s variables,
and it has access to the global variables.

The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters.
A function along with its lexical scope forms a closure

function greeting() {
var message = 'Hi';
function sayHi() {
alert(message);
}
return sayHi;
}
var hi = greeting();
hi(); //alerts Hi

See above example.
Normally, message variable only exists during the execution context of greeting() which means after successful execution of greeting() in second last line, its execution context is destroyed , so does message variable.
Message var is no longer accessible. But, when we call hi(), it alerts Hi. Message var is still accessible.
This is the magic of closure.
sayHi() forms a closure with its lexical scope

A closure consists of two parts: a function and the ability to remember its lexical scope even when that function executes outside its lexical scope.

Difference between Function statement and expression?

Major difference--> Function statements are hoisted while function expressions are not.

Top comments (0)