JavaScript functions: First-class objects
23 March 2009
In JavaScript, functions are first-class objects, meaning that they can be created, manipulated and passed around in the same manner as other objects/variables in JavaScript. For example, a function can be created, stored in a variable or even be the return value of another function, as seen below:
function getPower(power)
{
return function(x)
{
return Math.pow(x, power);
}
}
var x3 = getPower(3);
window.alert(x3(3)); // Outputs 27.
In the rather stupid and contrived example above, we make a function getPower()
that returns another function which raises the given value to the exponent supplied by calling getPower()
. (This is a bad way to do things for numerous reasons, but is just shown for the sake of providing a simple example)
We then call getPower
with a power of 3 and assign the returned function to the variable x3
, and the output is as expected. Defining “inline” functions this way and manipulating them is closely associated with the concept of anonymous functions.