Explain this code

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:

insectProperty = function(x) {
    document.write('honey bee' + x);
}

On the final line, you’re calling insectProperty, and passing it the string that will be used as x.

2 Likes

It’s not a callback, you’re just returning a function from multiplier.

So the value you’re assigning to insectProperty is the return value from multiplier. Which is a function. So insectProperty is a function.

Edit:

function multiplier(factor) {
    return function (x) {
      document.write(factor + x);
    }
}

So you are calling the function multiplier with the argument “honey bee” and it returns a value, so insectProperty is what multiplier returns:

let insectProperty = multiplier("honey bee");

Fill in those values:

let insectProperty = function (x) {
  return document.write("honey bee" + x);
}

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