function outer() {
const outerVar = "Hi i am outerVar";
function inner() {
const innerVar = "Hi i am innerVar";
console.log(outerVar);
console.log(innerVar);
}
return inner;
}
const innerFn = outer();
innerFn();
// Hi i am outerVar
// Hi i am innerVar
function makeFunction() {
const name = 'TK';
function displayName() {
console.log(name);
}
return displayName;
};
var counter = (function() { //exposed function references private state (the outer function’s scope / lexical environment) after outer returns.
var privateCounter = 0;
function changeBy(val) { privateCounter += val; }
return { increment: function() {changeBy(1); },
decrement: function() {changeBy(-1);},
value: function() {return privateCounter; }
};
})();
counter.increment(); counter.increment();
counter.decrement();
counter.value(); // 1
// Closures
//Almost mystical like feature that many developers fail to fully understand.
//We cannot create closures manually like how we create arrays and functions.
//Rather closures happen in certain situations. We just need to recognize
//those situations.
//Example:
const secureBooking = function () {
let passengerCount = 0; //Variable of the secureBooking Function
//returns a function
return function () {
passengerCount++; //Adding to the passengerCount
console.log(passengerCount);
};
};
const book = secureBooking(); //capture that function
book();
//In the above example we have a function called secureBooking
//That function returns another function, which we stored in book variable
//We then call the book() function and it adds to the passengerCount.
//But you may be wondering? How can it add to the passengerCount
//if the secureBooking has finished executing, shouldn't it not exist?
//This works because all functions have access to the variable environment
// in which they were created in. Meaning since secureBooking created
// the function which we stored in book. The book function now has
// access to the variable environment of secureBooking function.
outer = function() {
var a = 1;
var inner = function() {
console.log(a);
}
return inner; // this returns a function
}
var fnc = outer(); // execute outer to get inner
fnc();
func main() {
x := 0
increment := func() int {
x++
return x
}
fmt.Println(increment())
fmt.Println(increment())
}
function add(a) {
return function(b) {
return a + b;
};
}
let addTen = add(10);
let addSeven = addTen(7);
console.log(addSeven); // 17
def say():
greeting = 'Hello'
def display():
print(greeting)
display()
Code language: Python (python)