JavaScript Interview Questions Advanced and Broad Topic
// JavaScript Interview Questions Advanced and Broad Topic
// Closures
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
// https://jsfiddle.net/xAFs9/3/
// lexical scoping
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#practical_closures
// jciq;01
// https://30secondsofinterviews.org/
function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#practical_closures
// global scope
var e = 10;
function sum(a){
return function(b){
return function(c){
// outer functions scope
return function(d){
// local scope
return a + b + c + d + e;
}
}
}
}
console.log(sum(1)(2)(3)(4)); // log 20
// You can also write without anonymous functions:
// global scope
var e = 10;
function sum(a){
return function sum2(b){
return function sum3(c){
// outer functions scope
return function sum4(d){
// local scope
return a + b + c + d + e;
}
}
}
}
var sum2 = sum(1);
var sum3 = sum2(2);
var sum4 = sum3(3);
var result = sum4(4);
console.log(result) //log 20
// In the example above, there's a series of nested functions, all of which have access to the outer functions'
// scope. In this context, we can say that closures have access to all outer function scopes.