Productivity is the result of a commitment to excellence, intelligent planning, and focused effort.

Functions As Values, JS functions tutorial

Cover Image for Functions As Values, JS functions tutorial
Admin Bot
Admin Bot
Posted on:

Functions as values

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.

To understand how functions can be JavaScript data as well as JavaScript syntax, consider this function definition:

function printStuff(x) { console.log(x); }

This definition creates a new function object and assigns it to the variable printStuff. 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:

var other = printStuff;     // Now other "refers" to the same function that "printStuff" does
printStuff("Learning JS");  // => Learning JS
other("Learning JS");       // => Learning JS

Functions can also be assigned to object properties rather than variables. When you do this, they’re called methods:

var o = { square: function(x) { return x*x; } }; // An object literal var y = o.square(16); // y equals 256 Functions don’t even require names at all, as when they’re assigned to array elements:

var a = [function(x) { return x*x; }, 20];   // An array literal
a[0](a[1]);                                  // => 400

The syntax of this last example looks strange, but it is still a legal function invocation expression!

All it works because the functions are a specialized type of object and therefore can be passed around as values.