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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read 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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay