DEV Community

Cover image for Closure ๐Ÿซฅ
_Khojiakbar_
_Khojiakbar_

Posted on

Closure ๐Ÿซฅ

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.

Image description

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 !!!
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

// 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
Enter fullscreen mode Exit fullscreen mode

// 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!
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

Every function has an associated closure, not just inner functions. Function nesting is not required.