Functions as Values in JavaScript

A function binding usuallyjust acts as a name for a specific piece of the pro­gram. Such a binding is defined once and never changed. This makes it easy to confuse the function and its name.

But the two are different. A function value can do all the things that other values can do—you can use it in arbitrary expressions, not just call it.

It is possible to store a function value in a new binding, pass it as an argu­ment to a function, and so on. Similarly, a binding that holds a function is still just a regular binding and can, if not constant, be assigned a new value, like so:

let launchMissiles = function() {

missileSystem.launch(“now”);

};

if (safeMode) {

launchMissiles = function() {/* do nothing */};

}

In Chapter 5, we will discuss the interesting things that can be done by passing around function values to other functions.

Source: Haverbeke Marijn (2018), Eloquent JavaScript: A Modern Introduction to Programming,

No Starch Press; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *