Functions As Values
The most important features of functions are that they can be defined and invoked. Function definition and invocation are syntactic features of JavaScript and of most other programming languages. In JavaScript, however, functions are not only syntax but also values, which means they can be assigned to variables, stored in the properties of objects or the elements of arrays, passed as arguments to functions, and so on.[12]
To understand how functions can be JavaScript data as well as JavaScript syntax, consider this function definition:
functionsquare(x){returnx*x;}
This definition creates a new function object and assigns it to
the variable square. The name of a
function is really immaterial; it is simply the name of a variable
that refers to the function object. The function can be assigned to
another variable and still work the same way:
vars=square;// Now s refers to the same function that square doessquare(4);// => 16s(4);// => 16
Functions can also be assigned to object properties rather than variables. When you do this, they’re called methods:
varo={square:function(x){returnx*x;}};// An object literalvary=o.square(16);// y equals 256
Functions don’t even require names at all, as when they’re assigned to array elements:
vara=[function(x){returnx*x;},20];// An array literala[0](a[1]);// => 400
The syntax of this last example looks strange, but it is still a legal function invocation expression!
Example 8-2 demonstrates the kinds ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access