Functions

Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. To use a function, you must define it somewhere in the scope from which you wish to call it.

See also theexhaustive reference chapter about JavaScript functionsto get to know the details.

Defining functions

Function declarations

Afunction definition(also called afunction declaration,orfunction statement) consists of thefunctionkeyword, followed by:

  • The name of the function.
  • A list of parameters to the function, enclosed in parentheses and separated by commas.
  • The JavaScript statements that define the function, enclosed in curly braces,{ /*… */ }.

For example, the following code defines a simple function namedsquare:

js
functionsquare(number){
returnnumber*number;
}

The functionsquaretakes one parameter, callednumber.The function consists of one statement that says to return the parameter of the function (that is,number) multiplied by itself. Thereturnstatement specifies the value returned by the function, which isnumber * number.

Parameters are essentially passed to functionsby value— so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function,the change is not reflected globally or in the code which called that function.

When you pass an object as a parameter, if the function changes the object's properties, that change is visible outside the function, as shown in the following example:

js
functionmyFunc(theObject){
theObject.make="Toyota";
}

constmycar={
make:"Honda",
model:"Accord",
year:1998,
};

console.log(mycar.make);// "Honda"
myFunc(mycar);
console.log(mycar.make);// "Toyota"

When you pass an array as a parameter, if the function changes any of the array's values, that change is visible outside the function, as shown in the following example:

js
functionmyFunc(theArr){
theArr[0]=30;
}

constarr=[45];

console.log(arr[0]);// 45
myFunc(arr);
console.log(arr[0]);// 30

Function expressions

While the function declaration above is syntactically a statement, functions can also be created by afunction expression.

Such a function can beanonymous;it does not have to have a name. For example, the functionsquarecould have been defined as:

js
constsquare=function(number){
returnnumber*number;
};

console.log(square(4));// 16

However, a namecanbe provided with a function expression. Providing a name allows the function to refer to itself, and also makes it easier to identify the function in a debugger's stack traces:

js
constfactorial=functionfac(n){
returnn<2?1:n*fac(n-1);
};

console.log(factorial(3));// 6

Function expressions are convenient when passing a function as an argument to another function. The following example shows amapfunction that should receive a function as first argument and an array as second argument:

js
functionmap(f,a){
constresult=newArray(a.length);
for(leti=0;i<a.length;i++){
result[i]=f(a[i]);
}
returnresult;
}

In the following code, the function receives a function defined by a function expression and executes it for every element of the array received as a second argument:

js
functionmap(f,a){
constresult=newArray(a.length);
for(leti=0;i<a.length;i++){
result[i]=f(a[i]);
}
returnresult;
}

constcube=function(x){
returnx*x*x;
};

constnumbers=[0,1,2,5,10];
console.log(map(cube,numbers));// [0, 1, 8, 125, 1000]

In JavaScript, a function can be defined based on a condition. For example, the following function definition definesmyFunconly ifnumequals0:

js
letmyFunc;
if(num===0){
myFunc=function(theObject){
theObject.make="Toyota";
};
}

In addition to defining functions as described here, you can also use theFunctionconstructor to create functions from a string at runtime, much likeeval().

Amethodis a function that is a property of an object. Read more about objects and methods inWorking with objects.

Calling functions

Defininga function does notexecuteit. Defining it names the function and specifies what to do when the function is called.

Callingthe function actually performs the specified actions with the indicated parameters. For example, if you define the functionsquare,you could call it as follows:

js
square(5);

The preceding statement calls the function with an argument of5.The function executes its statements and returns the value25.

Functions must bein scopewhen they are called, but the function declaration can behoisted(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. TheshowProps()function (defined inWorking 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:

js
functionfactorial(n){
if(n===0||n===1){
return1;
}else{
returnn*factorial(n-1);
}
}

You could then compute the factorials of1through5as follows:

js
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 thatfunctions are themselves objects— and in turn, these objects have methods. (See theFunctionobject.) Thecall()andapply()methods can be used to achieve this goal.

Function hoisting

Consider the example below:

js
console.log(square(5));// 25

functionsquare(n){
returnn*n;
}

This code runs without any error, despite thesquare()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:

js
// All function declarations are effectively at the top of the scope
functionsquare(n){
returnn*n;
}

console.log(square(5));// 25

Function hoisting only works with functiondeclarations— not with functionexpressions.The following code will not work:

js
console.log(square(5));// ReferenceError: Cannot access 'square' before initialization
constsquare=function(n){
returnn*n;
};

Function scope

Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined.

In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function, and any other variables to which the parent function has access.

js
// The following variables are defined in the global scope
constnum1=20;
constnum2=3;
constname="Chamakh";

// This function is defined in the global scope
functionmultiply(){
returnnum1*num2;
}

console.log(multiply());// 60

// A nested function example
functiongetScore(){
constnum1=2;
constnum2=3;

functionadd(){
return`${name}scored${num1+num2}`;
}

returnadd();
}

console.log(getScore());// "Chamakh scored 5"

Scope and the function stack

Recursion

A function can refer to and call itself. There are three ways for a function to refer to itself:

  1. The function's name
  2. arguments.callee
  3. An in-scope variable that refers to the function

For example, consider the following function definition:

js
constfoo=functionbar(){
// statements go here
};

Within the function body, the following are all equivalent:

  1. bar()
  2. arguments.callee()
  3. foo()

A function that calls itself is called arecursive 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:

js
letx=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:

js
functionloop(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 theDOM) is easier via recursion:

js
functionwalkTree(node){
if(node===null){
return;
}
// do something with node
for(leti=0;i<node.childNodes.length;i++){
walkTree(node.childNodes[i]);
}
}

Compared to the functionloop,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:

js
functionfoo(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: 3

Nested functions and closures

You may nest a function within another function. The nested (inner) function is private to its containing (outer) function.

It also forms aclosure.A closure is an expression (most commonly, a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.

To summarize:

  • The inner function can be accessed only from statements in the outer function.
  • The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.

The following example shows nested functions:

js
functionaddSquares(a,b){
functionsquare(x){
returnx*x;
}
returnsquare(a)+square(b);
}

console.log(addSquares(2,3));// 13
console.log(addSquares(3,4));// 25
console.log(addSquares(4,5));// 41

Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:

js
functionoutside(x){
functioninside(y){
returnx+y;
}
returninside;
}

constfnInside=outside(3);// Think of it like: give me a function that adds 3 to whatever you give it
console.log(fnInside(5));// 8
console.log(outside(3)(5));// 8

Preservation of variables

Notice howxis preserved wheninsideis returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call tooutside.The memory can be freed only when the returnedinsideis no longer accessible.

This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them.

Multiply-nested functions

Functions can be multiply-nested. For example:

  • A function (A) contains a function (B), which itself contains a function (C).
  • Both functionsBandCform closures here. So,Bcan accessA,andCcan accessB.
  • In addition, sinceCcan accessBwhich can accessA,Ccan also accessA.

Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is calledscope chaining.(The reason it is called "chaining" is explained later.)

Consider the following example:

js
functionA(x){
functionB(y){
functionC(z){
console.log(x+y+z);
}
C(3);
}
B(2);
}
A(1);// Logs 6 (which is 1 + 2 + 3)

In this example,CaccessesB'syandA'sx.

This can be done because:

  1. Bforms a closure includingA(i.e.,Bcan accessA's arguments and variables).
  2. Cforms a closure includingB.
  3. BecauseC's closure includesBandB's closure includesA,thenC's closure also includesA.This meansCcan accessbothBandA's arguments and variables. In other words,Cchainsthe scopes ofBandA,in that order.

The reverse, however, is not true.Acannot accessC,becauseAcannot access any argument or variable ofB,whichCis a variable of. Thus,Cremains private to onlyB.

Name conflicts

When two arguments or variables in the scopes of a closure have the same name, there is aname conflict.More nested scopes take precedence. So, the innermost scope takes the highest precedence, while the outermost scope takes the lowest. This is the scope chain. The first on the chain is the innermost scope, and the last is the outermost scope. Consider the following:

js
functionoutside(){
constx=5;
functioninside(x){
returnx*2;
}
returninside;
}

console.log(outside()(10));// 20 (instead of 10)

The name conflict happens at the statementreturn x * 2and is betweeninside's parameterxandoutside's variablex.The scope chain here is {inside,outside,global object}. Therefore,inside'sxtakes precedences overoutside'sx,and20(inside'sx) is returned instead of10(outside'sx).

Closures

Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to).

However, the outer function doesnothave access to the variables and functions defined inside the inner function. This provides a sort of encapsulation for the variables of the inner function.

Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the duration of the outer function execution, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function.

js
// The outer function defines a variable called "name"
constpet=function(name){
constgetName=function(){
// The inner function has access to the "name" variable of the outer function
returnname;
};
returngetName;// Return the inner function, thereby exposing it to outer scopes
};
constmyPet=pet("Vivie");

console.log(myPet());// "Vivie"

It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.

js
constcreatePet=function(name){
letsex;

constpet={
// setName(newName) is equivalent to setName: function (newName)
// in this context
setName(newName){
name=newName;
},

getName(){
returnname;
},

getSex(){
returnsex;
},

setSex(newSex){
if(
typeofnewSex==="string"&&
(newSex.toLowerCase()==="male"||newSex.toLowerCase()==="female")
){
sex=newSex;
}
},
};

returnpet;
};

constpet=createPet("Vivie");
console.log(pet.getName());// Vivie

pet.setName("Oliver");
pet.setSex("male");
console.log(pet.getSex());// male
console.log(pet.getName());// Oliver

In the code above, thenamevariable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent" and "encapsulated" data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.

js
constgetCode=(function(){
constapiCode="0]Eal(eh&2";// A code we do not want outsiders to be able to modify…

returnfunction(){
returnapiCode;
};
})();

console.log(getCode());// "0]Eal(eh&2"

Note:There are a number of pitfalls to watch out for when using closures!

If an enclosed function defines a variable with the same name as a variable in the outer scope, then there is no way to refer to the variable in the outer scope again. (The inner scope variable "overrides" the outer one, until the program exits the inner scope. It can be thought of as aname conflict.)

js
constcreatePet=function(name){
// The outer function defines a variable called "name".
return{
setName(name){
// The enclosed function also defines a variable called "name".
name=name;// How do we access the "name" defined by the outer function?
},
};
};

Using the arguments object

The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:

js
arguments[i];

whereiis the ordinal number of the argument, starting at0.So, the first argument passed to a function would bearguments[0].The total number of arguments is indicated byarguments.length.

Using theargumentsobject, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can usearguments.lengthto determine the number of arguments actually passed to the function, and then access each argument using theargumentsobject.

For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

js
functionmyConcat(separator){
letresult="";// initialize list
// iterate through arguments
for(leti=1;i<arguments.length;i++){
result+=arguments[i]+separator;
}
returnresult;
}

You can pass any number of arguments to this function, and it concatenates each argument into a string "list":

js
console.log(myConcat(",","red","orange","blue"));
// "red, orange, blue,"

console.log(myConcat(";","elephant","giraffe","lion","cheetah"));
// "elephant; giraffe; lion; cheetah;"

console.log(myConcat(".","sage","basil","oregano","pepper","parsley"));
// "sage. basil. oregano. pepper. parsley."

Note:Theargumentsvariable is "array-like", but not an array. It is array-like in that it has a numbered index and alengthproperty. However, it doesnotpossess all of the array-manipulation methods.

See theFunctionobject in the JavaScript reference for more information.

Function parameters

There are two special kinds of parameter syntax:default parametersandrest parameters.

Default parameters

In JavaScript, parameters of functions default toundefined.However, in some situations it might be useful to set a different default value. This is exactly what default parameters do.

In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they areundefined.

In the following example, if no value is provided forb,its value would beundefinedwhen evaluatinga*b,and a call tomultiplywould normally have returnedNaN.However, this is prevented by the second line in this example:

js
functionmultiply(a,b){
b=typeofb!=="undefined"?b:1;
returna*b;
}

console.log(multiply(5));// 5

Withdefault parameters,a manual check in the function body is no longer necessary. You can put1as the default value forbin the function head:

js
functionmultiply(a,b=1){
returna*b;
}

console.log(multiply(5));// 5

For more details, seedefault parametersin the reference.

Rest parameters

Therest parametersyntax allows us to represent an indefinite number of arguments as an array.

In the following example, the functionmultiplyusesrest parametersto collect arguments from the second one to the end. The function then multiplies these by the first argument.

js
functionmultiply(multiplier,...theArgs){
returntheArgs.map((x)=>multiplier*x);
}

constarr=multiply(2,1,2,3);
console.log(arr);// [2, 4, 6]

Arrow functions

Anarrow function expression(also called afat arrowto distinguish from a hypothetical->syntax in future JavaScript) has a shorter syntax compared to function expressions and does not have its ownthis,arguments,super,ornew.target.Arrow functions are always anonymous.

Two factors influenced the introduction of arrow functions:shorter functionsandnon-bindingofthis.

Shorter functions

In some functional patterns, shorter functions are welcome. Compare:

js
consta=["Hydrogen","Helium","Lithium","Beryllium"];

consta2=a.map(function(s){
returns.length;
});

console.log(a2);// [8, 6, 7, 9]

consta3=a.map((s)=>s.length);

console.log(a3);// [8, 6, 7, 9]

No separate this

Until arrow functions, every new function defined its ownthisvalue (a new object in the case of a constructor, undefined instrict modefunction calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.

js
functionPerson(){
// The Person() constructor defines `this` as itself.
this.age=0;

setInterval(functiongrowUp(){
// In nonstrict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
},1000);
}

constp=newPerson();

In ECMAScript 3/5, this issue was fixed by assigning the value inthisto a variable that could be closed over.

js
functionPerson(){
// Some choose `that` instead of `self`.
// Choose one and be consistent.
constself=this;
self.age=0;

setInterval(functiongrowUp(){
// The callback refers to the `self` variable of which
// the value is the expected object.
self.age++;
},1000);
}

Alternatively, abound functioncould be created so that the properthisvalue would be passed to thegrowUp()function.

An arrow function does not have its ownthis;thethisvalue of the enclosing execution context is used. Thus, in the following code, thethiswithin the function that is passed tosetIntervalhas the same value asthisin the enclosing function:

js
functionPerson(){
this.age=0;

setInterval(()=>{
this.age++;// `this` properly refers to the person object
},1000);
}

constp=newPerson();