Closures

Hi,
I’m struggling to understand this bloke of code from the Eloquent JavaScript (2018) - Chapter 3.
Wondering if anyone could help me understand what is going on here?
Thanks!

function multiplier(factor) {
return number => number * factor;
}

let twice = multiplier(2);
console.log(twice(5));
// → 10

function multiplier(factor) { // factor (2) passed as argument by function invocation
	console.log(factor); // output: 2
	return number => number * factor; // function returned to let twice
}

let twice = multiplier(2); // returns a function: number => number * factor (passes 2 as factor)
console.log(multiplier(2)); // output: number => number * factor
console.log(twice(5)); // output 10

Edited after clarification by @mtf

1 Like

On the face of it, we can see that factor is a number.

The factory function then returns a function with that factor as a constant. In the example above, twice is the returned function with a constant set at 2. Any value we pass into that function will return double its value.


There are two kinds of factory functions, one that returns an object with supplied property values, and one that returns a function with a supplied constant, as above. The latter may sometimes be called a function factory.

2 Likes

Thank you for your clarification. I edited my previous post and hope it is clearer now.

3 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.