I was learning Callback functions from a Youtube video and was able to write this piece of code.
function multiplier(factor) {
return x => document.write(factor + x);
}
let insectProperty = multiplier("honey bee");
insectProperty(" loves to bite");
But I don’t understand the logic here. I know what this code is doing but I have no idea how x is working. Like insectProperty is a variable then how does it take the place of x when given an argument. Can someone please explain every line and what is happening here?
A similar example like this may help a lot.
Thanks in advance.
Sometimes I find it easier to write things out in ES5 syntax to begin with. multiplier is returning a function, and in this case the function now assigned to insectProperty will look like this:
What that code snippet is demonstrating is something called a closure through the use of a nested function. The function insectProperty is nested in multiplier such that all the variables in multiplier are accessible to the insectProperty function but not the other way round. A closure is created when the insectProperty function is somehow made available to any scope outside the outer function.
As another example consider:
function createNum(x) {
return {
add_3: function() {
x = x + 3;
},
minus_1: function() {
x = x - 1;
},
get_x: function() {
return x;
}
}
}
let num = createNum(0);
num.get_x(); // output: 0
num.add_3() ;
num.minus_1();
num.get_x(); // output: 2