Closures | javascript

Definition

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 `;
                    }
                    else{
                        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);
        console.log(myCarPrice1);
        console.log(myCarPrice2);
         

You can read a lot more about closures on mdn





Services
  • SEO
  • Online Advertising
  • Online Ordering For Restaurants
  • Data Analytics

  • External Resources 4 Developers
  • CSS Tricks
  • MDN

  • Dash-Intel.com is a Power BI and Tableau resource site around data visualizations and building business dashboards.

    Data Analytics consultants in Edmonton, Alberta specializing in Tableau and marketing analytics

    Copyright 2020 Dash-Intel.com Terms / All rights reserved.