Skip to main content

What is Closure

We know, A closure is a function that gives us access to an outer function scope's variable from an inner function. To know more about closure please click here..

What will be the output of the following IIFE ?

let count = 0;
(function immediate() {
if (count === 0) {
let count = 1;
console.log(count); // What is logged?
}
console.log(count); // What is logged?
})();

Technically this function describes the scope of a variable. Now let us crack the code.

let count = 0;
// this count variable has global scope.
(function immediate() {
// global count variable has access with in function also
// so below if compares the value of global count with zero
if (count === 0) {
let count = 1;
// this count variable's scope is with in if block. Because let is block scoped.
console.log(count); // logs 1
}
// this portion is out of if scope so here the global scope count can be accessed.
console.log(count); // logs 0
})();

What will be the output of the following closure ?

function outer(n) {
let count = n;
return function inner(){
if(count === 0){
let count = 1;
console.log(count);
}
console.log(count);
}
};

let x = outer(0);
x();

Output :

1
0

What will be the output of the following closure ?

function outer(n) {
let count = n;
return function inner(){
if(count === 0){
let count = 1;
console.log(count);
}
console.log(count);
}
};

let x = outer(5);
x();

Output :

5

What will be the output of the following closure ?

function outer(n) {
let count = n;
return function inner(){
if(count === 0){
let count = 1;
console.log(count);
}
console.log(count);
}
};

let x = outer();
x();

Output :

undefined

Hindi Video Tutorial

English Video Tutorial