Closures | javascript


Definition: Closure is when an inner function has access to the variables and parameters of it's parent function, even after the parent function has returned.

Closure with no parameters

To get a grasp of exactly what is happening, try the following code:

     function greeting(){
       const name = "Anna";
       console.log('this is the outer function yay!');
        return function(){
            console.log('this is the inner function booya!');
            console.log(`Hi my Name is ${name}`);
     // running the closure.
     const hi = greeting()();

     // if you simply run greeting(), then nothing happens as the inner function was not called.
     // this means the inner function has access to name even after the outer function has returned.

We use the concept of closure scope chain to call the outer function first and then the nested inner functions. If you try running only greeting() then only the outer function will get called.

Example of closure with parameters

Again, use the pattern of declaring a function and then returning an anonymous function within the parent function to make use of closures

        function calculateCarPrice(make){
        const message = `The price of your ${make} is: `;
        const currentYear = new Date().getFullYear();

            return function(dateOfPurchase){
                    if(make === 'honda'){
                        return `The price of your ${currentYear - dateOfPurchase} year old ${make} is: $20,000 `;
                        return `The price of your ${currentYear - dateOfPurchase} year old ${make} could not be determined`;

        // run the closure above
        const myCarPrice1 = calculateCarPrice('honda')(2000);
        const myCarPrice2 = calculateCarPrice('Tesla')(2011);

You can read a lot more about closures on mdn

Dash-Intel is a Power BI and Tableau resource site for data visualization and building BI dashboards.

Data Analyst & Consultant

Copyright 2015-2023 Terms