Closure Road Sign with dramatic clouds and sky.

Closures

When a function runs, it goes through its code, then completes. Everything goes out of scope. There are times when we might want some information to “hang around”. Let’s start by looking at an example…

let app = (function(){
    let animalName = ‘Bongo’;
    let getName = function(){
        return animalName;
    };
})();
console.log(app.getName());

Within our IIFE, we have a variable (animalName). We also have a nested function that returns the animalName variable. The problem is that if you run this, it will return that app is undefined because the function is complete and there is no closure to have any of the function’s information live on. You might think that the return statement does that here, but it is within the nested function. So it returns to the outer function. We need to create a closure…

let app = (function(){
    let animalName = ‘Bongo’;
    let getName = function(){
        return animalName;
    };
    return {
        getName: getName
    };
})();
console.log(app.getName());

Now, we will get the name “Bongo” returned because the outer return statement creates the closure. It returns a reference to the function.

Happy Coding!

Clay Hess

Share this post

Share on facebook
Share on google
Share on twitter
Share on linkedin
Share on pinterest
Share on print
Share on email
Skip to content