Skip to main content

Closures

28th October, 2022

Updated: 28th October, 2022

    You will frequently encounter closures in Node.js. If you are just interested in the front-end, think back to our original example. If you want to write a function that considers user input at two separate stages of your app, you may want to consider a closure!

    https://jsfiddle.net/semL3c66/

    https://medium.freecodecamp.com/javascript-closures-explained-by-mailing-a-package-4f23e9885039#.tusqys1zn

    function packBox(item) {
      // Code that puts item in the box
      console.log(item);
    
      function addressPackage(address) {
        // Code that writes the address label
        console.log(address + '. My initialised value was: ' + item + '');
      }
      return addressPackage;
    }
    
    var closureDemo = packBox('Initialising with a stored value')
    // do "other things"
    console.log('other things')
    closureDemo('Ive done "other things" and now Im calling closureDemo')
    
    
    // can also be run like:
    
    var closureDemo = packBox('initilisation value')('data we might have retrieved from another site ajax call');
    closureDemo;

    b10baa2a-e0aa-4c5c-bc22-95a24c0497bf

    Created on: 28th October, 2022

    Last updated: 28th October, 2022

    Source: JavaScript Closures Explained by Mailing a Package

    Tagged With: