Tinkle Pooplebottham Tinkle Pooplebottham - 14 days ago 6
Javascript Question

Trying to understand this function as value

I got this code from the Headfirst Javascript book. I changed the function names to be clearer. I'm trying to wrap my head around this.

I assigned add to the function outer with a number. That number remains for some reason - returns a reference to inner with n = num (which returns the added values?

Anytime I change outers n value, the inner will use that new value?
I believe I'm right on that. Is there anywhere I can read more about it? See better examples? Or can anyone explain this better?



function outer(n) {
var inner = function(x) { //or x = 0
return n + (x || 0); //added default 0 for testing to prevent NaN
}
return inner;
}
var num = 2;
var add = outer(num);
console.log(`Adding 2 to num(${num}): ${add(2)}`);

add = outer(5);
console.log(add());
console.log(add(2));




Answer

In JavaScript, functions can act as regular data. If you are OK with the idea of passing a number or string around, then passing a function around is no different. This allows you the ability to do some very cool and powerful things.

Here, instead of the add function simply giving you your numeric answer, it's giving you back a function with your number embedded into it. This means that add doesn't really add anything, add is a function for creating functions (similar to the idea of a "Factory" in class based programming).

Changing the names may make things easier:

function createAddFunction(numberThatWillBeHardWiredIntoReturnedFunction) {
    var resultingFunction= function(x) { //or x = 0
    return numberThatWillBeHardWiredIntoReturnedFunction + (x || 0); 
  }
  return resultingFunction;
}
var num = 2;

// This will cause add to be a function that is hard-wired to add 2 to another number
var add = createAddFunction(num);  
console.log(`Adding 2 to num(${num}): ${add(2)}`);

// This will cause add to be a function that is hard-wired to add 5 to another number
add = createAddFunction(5);
console.log(add());
console.log(add(2));
Comments