Here in the post, I have posted all the possible interview questions and answers on closure.
If you are not familiar with the closure, I would highly recommend you to go to my post on closure. Once you are comfortable with the topic, you can attempt these questions. All the answers are given at the end of the post.
Here are the output of all the questions:
Output 1:
Output 4:
Output5:
Output 6:
Thank you !!
//Question 1
function foo() {
var a = 5
function bar() {
console.log(a)
}
return bar;
}
var baz = foo()
baz()
// Question 2
function outer(a) {
var b = 2
function inner() {
var c = 5
console.log(a * b * c)
}
return inner;
}
var multiply = outer(5)
multiply()
// Question 3
const arr = [10, 20, 30, 40, 50]
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log('Index: ' + i + ', element: ' + arr[i])
}, 1000)
}
// Question 4
for (var i = 0; i < 5; i++) {
setTimeout(function(i) {
return function() {
console.log('The value of i is: ' + i);
}
}(i), 1000);
}
//Question 5
for (let i = 0; i < 5; i++) { setTimeout(function() { console.log('The value of i is: ' + i); }, 1000); }
for (let i = 0; i < 5; i++) { setTimeout(function() { console.log('The value of i is: ' + i); }, 1000); }
// Question 6
var fn;
function foo() {
var a = 5;
function baz() {
console.log(a);
}
fn = baz;
}
function bar() {
fn();
}
foo();
bar();
Here are the output of all the questions:
Output 1:
5
Output 2:
50
Output 3:
Index: 5, element: undefined
Index: 5, element: undefined
Index: 5, element: undefined
Index: 5, element: undefined
Index: 5, element: undefined
The value of i is: 0
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
The value of i is: 0
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
5
Hope these questions were helpful. Lemme know if you find any difficulty or have any query, in the comment section. Support by subscribing and sharing.Thank you !!
Comments
Post a comment