In JavaScript, a closure is a feature where an inner function has access to the outer (enclosing) functionโs variables. This includes the outer functionโs parameters, variables declared within the outer function, and variables declared in the global scope.
Example:
function outherFunction(outVar) {
let icon = 'โบ๏ธ'
return function innerFunction(innerVar) {
let excMark = '!!!'
console.log('Outer:', outVar)
console.log('Inner:', innerVar)
console.log(`Together: ${icon} ${outVar} ${innerVar} ${excMark}`)
}
}
let newFN = outherFunction('Hello')
newFN('World')
// Outer: Hello
// Inner: World
// Together: โบ๏ธ Hello World !!!
FUNNY EXAMPLES FOR CLOSURE
EXAMPLE 1:
function aboutTeller(lie) {
return {
tellAbout : function() {
console.log(lie)
},
changeAbout : function(truth) {
lie = truth
}
}
}
const aboutMe = aboutTeller('I am senior developer.');
aboutMe.tellAbout()
aboutMe.changeAbout('I am junior developer.');
aboutMe.tellAbout()
// I am senior developer.
// I am junior developer.
EXAMPLE 2:
// A collector squirrel
function collectorSquirrel() {
let nuts = 0;
return {
stored : function (numNuts) {
nuts += numNuts;
console.log(`Squirrel stored ${numNuts} nuts into the wood.`)
},
has : function () {
console.log(`Squirrel has ${nuts} nuts.`)
}
}
}
let mySquirrel = collectorSquirrel()
mySquirrel.stored(3)
mySquirrel.has()
// Squirrel stored 3 nuts into the wood.
// Squirrel has 3 nuts.
// EXAMPLE 3:
// Time traveler
function timeTravel() {
time = new Date().getFullYear()
return {
travelTo: function(desiredTime) {
console.log(`Hello! Welcome to ${time + desiredTime}. Have a nice time!`)
},
reset: function() {
time = new Date().getFullYear()
console.log(time)
}
}
}
let thisTime = timeTravel()
thisTime.travelTo(10) // Hello! Welcome to 2034. Have a nice time!
thisTime.reset() // 2024
// EXAMPLE 4:
// The Motivational Coach
function motivationalCoach () {
const phrases = [
"You're doing great!",
"Keep up the good work!",
"You can do it!",
"Believe in yourself!"
];
return function() {
let phrase = phrases[Math.floor(Math.random() * phrases.length)];
console.log(phrase)
}
}
let motivateMe = motivationalCoach()
motivateMe() // You can do it!
Top comments (1)
Every function has an associated closure, not just inner functions. Function nesting is not required.