JS Revision - Closure

An inner function that has access to an outer function's scope.

by andfinally

JavaScript

/*
 * Inner function has access to outer function's variables and parameters.
 */

function makeName(forename, surname) {
  var intro = "Your name is ";

  function makePhrase() {
    return intro + forename + ' ' + surname;
  };
  return makePhrase();
}

console.log(makeName('Bob', 'Simpkins'));

/* 
 * The inner function maintains this access even after the outer
function has returned.
*/

function makeName(forename) {
  var intro = "Your name is ";
  return function(surname) {
    return intro + forename + ' ' + surname;
  }
}

var myName = makeName('Bob');
console.log(myName('Simpkins'));

/*
 * The closure stores a reference to the outer function's variables,
 not the values.
 */

function celebrityID() {
  var theID = 999;

  function get() {
    return theID;
  }

  function set(newID) {
    theID = newID;
  }
  return {
    get: get,
    set: set
  }
}

celebrityID();
celebrityID.get();
celebrityID.set(1);
celebrityID.get();