Calling functions
Defining a function does not execute it. Defining it names the function and specifies what to do when the function is called.
Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function square, you could call it as follows:
square(5);
The preceding statement calls the function with an argument of 5. The function executes its statements and returns the value 25.
Functions must be in scope when they are called, but the function declaration can be hoisted (appear below the call in the code). The scope of a function declaration is the function in which it is declared (or the entire program, if it is declared at the top level).
The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The showProps() function (defined in Working with objects) is an example of a function that takes an object as an argument.
A function can call itself. For example, here is a function that computes factorials recursively:
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
}
You could then compute the factorials of 1 through 5 as follows:
console.log(factorial(1)); // 1
console.log(factorial(2)); // 2
console.log(factorial(3)); // 6
console.log(factorial(4)); // 24
console.log(factorial(5)); // 120
There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime.
It turns out that functions are themselves objects — and in turn, these objects have methods. (See the Function object.) The call() and apply() methods can be used to achieve this goal.
Function hoisting
Consider the example below:
console.log(square(5)); // 25
function square(n) {
return n * n;
}
This code runs without any error, despite the square() function being called before it's declared. This is because the JavaScript interpreter hoists the entire function declaration to the top of the current scope, so the code above is equivalent to:
// All function declarations are effectively at the top of the scope
function square(n) {
return n * n;
}
console.log(square(5)); // 25
Function hoisting only works with function declarations — not with function expressions. The following code will not work:
console.log(square(5)); // ReferenceError: Cannot access 'square' before initialization
const square = function (n) {
return n * n;
};Recursion
A function can refer to and call itself. It can be referred to either by the function expression or declaration's name, or via any in-scope variable that refers to the function object. For example, consider the following function definition:
const foo = function bar() {
// statements go here
};
Within the function body, you can refer to the function itself either as bar or foo, and call itself using bar() or foo().
A function that calls itself is called a recursive function. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case).
For example, consider the following loop:
let x = 0;
// "x < 10" is the loop condition
while (x < 10) {
// do stuff
x++;
}
It can be converted into a recursive function declaration, followed by a call to that function:
function loop(x) {
// "x >= 10" is the exit condition (equivalent to "!(x < 10)")
if (x >= 10) {
return;
}
// do stuff
loop(x + 1); // the recursive call
}
loop(0);
However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (such as the DOM) is easier via recursion:
function walkTree(node) {
if (node === null) {
return;
}
// do something with node
for (const child of node.childNodes) {
walkTree(child);
}
}
Compared to the function loop, each recursive call itself makes many recursive calls here.
It is possible to convert any recursive algorithm to a non-recursive one, but the logic is often much more complex, and doing so requires the use of a stack.
In fact, recursion itself uses a stack: the function stack. The stack-like behavior can be seen in the following example:
function foo(i) {
if (i < 0) {
return;
}
console.log(`begin: ${i}`);
foo(i - 1);
console.log(`end: ${i}`);
}
foo(3);
// Logs:
// begin: 3
// begin: 2
// begin: 1
// begin: 0
// end: 0
// end: 1
// end: 2
// end: 3Immediately Invoked Function Expressions (IIFE)
An Immediately Invoked Function Expression (IIFE) is a code pattern that directly calls a function defined as an expression. It looks like this:
(function () {
// Do something
})();
const value = (function () {
// Do something
return someValue;
})();
Instead of saving the function in a variable, the function is immediately invoked. This is almost equivalent to just writing the function body, but there are a few unique benefits:
- It creates an extra scope of variables, which helps to confine variables to the place where they are useful.
- It is now an expression instead of a sequence of statements. This allows you to write complex computation logic when initializing variables.
For more information, see the IIFE glossary entry.