Closures - Javascript Function

Javascript examples for Function:Closure

Description

Closures

Demo Code

function retirement(retirementAge) {
  var a = " years left until retirement.";
  return function(yearOfBirth) {
    var age = 2017 - yearOfBirth;
    console.log((retirementAge - age) + a);
  }//  w  w  w . j av a  2 s .  c om
}

// Retirement age is 66 in the US, so:
var retirementUS = retirement(66);
// Now call this function and pass your birth year into it, and it will calculate how many years you have until retirement:
retirementUS(1979);

// Same thing, written a different way:
// retirement(66)(1979);

var retirementGermany = retirement(65);
retirementGermany(1979);

var retirementIceland = retirement(67);
retirementIceland(1979);

Related Tutorials