DEV Community

Cover image for Closure 🫥
_Khojiakbar_
_Khojiakbar_

Posted on

1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more