Can anyone explain this function call?

How does the function call ‘retirementUS(1990)’ connect to ‘yearOfBirth’ parameter inside the anonymous function?

function retirement(retirementAge){

	var a = ' years left until retirement.!';

	return function(yearOfBirth){
		var age = 2016 - yearOfBirth;
		console.log((retirementAge - age) + a) 
	}
}

var retirementUS = retirement(66);
retirementUS(1990);

The retirement function returns a function. Yes, the function it is returning is anonymous as defined in the retirement function but you are setting it to a variable with the line:

var retirementUS = retirement(66);

So that anonymous function being returned by the retirement function is not so anonymous anymore, it has a name (retirementUS).

The function being returned by the retirement function takes one argument (yearOfBirth), so the new function retirementUS also takes that same argument.

1 Like

Because your call to retirement(66) stored that data and returned a function. If I console out retirementUS, I get:

ƒ (yearOfBirth) {
    var age = 2016 - yearOfBirth;
    console.log(retirementAge - age + a);
  }

But those variables are wrapped in an enclosure that binds them to that, so it is really:

ƒ (yearOfBirth) {
    var age = 2016 - yearOfBirth;
    console.log(66 - age + ' years left until retirement.!');
  }

Scope is a complicated subject, don’t get frustrated.

Also, a shorter (but not necessarily better) way to run this would be

retirement(66)(1990);
1 Like