Skip to main content

Posts

Showing posts with the label Closure

Javascript Closure Interview Questions and Answers - 6

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 onclosure. Once you are comfortable with the topic, you can attempt these questions. All the answers are given at the end of the post.

//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…

Come Closure in Javascript

What is a closure? If we want to derive a definition,we can say, A closure is a feature of Javascript where inner function has access to the outer (enclosing) function’s variables—scope chain. This scope chains means inner function has: access to its own scope (variables defined between its curly brackets and its parameters),access to the outer function’s variables and parameters, access to the global variables. Now we will look into it in detail. Consider following example
var globalVar = "xyz"; function outerFunc(outerArg) { var outerVar = 'Alex'; function innerFunc(innerArg) { var innerVar = 'Chris'; console.log("globalVar = " + globalVar); console.log("outerArg = " + outerArg); console.log("innerArg = " + innerArg); console.log("outerVar = " + outerVar); console.log("innerVar = " + innerVar); } innerFunc(456); } outerFunc(123); In this example, i…