A function is a block of code with a name that you can run again and again. You give it values (parameters), it does some work, and it can send a result back with return.
In JavaScript every function is also an object of the built-in Function type. That means a function can be stored in a variable, passed to another function, returned from a function, and it has its own methods and properties such as name and length.
You can put a function in a variable, give it to another function as a callback, or return it. The code only runs when you call it with parentheses: greet().
Syntax
JavaScript Syntax
Write a function, call it, and use the four Function methods:
JavaScript
function greet(name) { // function declaration
return "Hello, " + name;
}
const shout = (text) => text.toUpperCase(); // arrow function
console.log(greet("Ava")); // "Hello, Ava"
console.log(shout("hi")); // "HI"
console.log(greet.call(null, "Ben")); // run now, arguments one by one
console.log(greet.apply(null, ["Cy"])); // run now, arguments in an array
const hello = greet.bind(null, "Di"); // new function with "Di" filled in
console.log(hello()); // "Hello, Di"
console.log(greet.toString().length > 0); // the code as text
Reference
Core Ideas
Ideas every Function tutorial in this series builds on:
Idea
Example
Remember
Parameter
function add(a, b) { ... }
A name inside the parentheses that receives a value
Argument
add(2, 3)
The real value you pass when you call the function
return
return a + b;
Sends a result back and stops the function
this
this.name
The object a function was called on; it depends on how you call it
name
greet.name
The name of the function, as text
length
greet.length
How many parameters the function declares
Closure
return function () { count++; }
An inner function that remembers the variables around it
Callback
list.map(double)
A function given to another function to call later
Compare
Ways to Write a Function
These styles all create functions. They differ in a few small details:
Style
Example
Has its own this?
Declaration
function add(a, b) { return a + b; }
Yes
Expression
const add = function (a, b) { return a + b; };
Yes
Arrow function
const add = (a, b) => a + b;
No, it uses the surrounding this
Method shorthand
const calc = { add(a, b) { return a + b; } };
Yes
Constructor
const add = new Function("a", "b", "return a + b");
Yes (rarely used)
Start with declarations and arrow functions. A declaration can be called before the line where it is written, because JavaScript moves it to the top (this is called hoisting). An arrow function or an expression stored in a const cannot.
Behavior
How Functions Work
Defining is not running
Writing function greet() { ... } only creates the function. Its code runs when you call it with parentheses, greet(). Without the parentheses you only get the function itself.
Arguments fill parameters in order
The first argument goes into the first parameter, and so on. A missing argument becomes undefined, and an extra argument is ignored unless you collect it with ...rest.
return ends the function
The first return that runs sends a value back and stops the function. A function without return gives back undefined.
this depends on the call
A regular function gets its this from how it is called: user.greet() uses user. An arrow function does not have its own this. The methods call(), apply() and bind() let you choose it.
Inner functions remember
A function created inside another function keeps access to the variables around it, even after the outer function has finished. This is a closure. Example 3 shows it.
Practice
Real-Life Uses
Functions are the main way to organize JavaScript code. Typical places you will use them:
Use
What it does
Reuse code
Write a calculation once, call it from many places with different values.
Callbacks and events
Give a function to setTimeout(), map() or addEventListener() so it runs later.
Methods of objects
Put functions inside objects to describe what that object can do, such as cart.addItem().
Private data
Use a closure to keep a counter or setting hidden, with only a few functions allowed to change it.
Code
JavaScript Examples
Three short programs. Each one prints plain text, so the output is the same in Node.js and in the browser console.
Example 1 — Write the Same Function Four Ways
A declaration, an expression, an arrow function and an object method all add two numbers.
JavaScript
function addDeclaration(a, b) {
return a + b;
}
const addExpression = function (a, b) {
return a + b;
};
const addArrow = (a, b) => a + b;
const calculator = {
add(a, b) {
return a + b;
}
};
console.log("Declaration: " + addDeclaration(2, 3));
console.log("Expression: " + addExpression(2, 3));
console.log("Arrow: " + addArrow(2, 3));
console.log("Method: " + calculator.add(2, 3));
Declaration. The classic form starts with the word function and a name.
Expression and arrow. Both store a function in a const. The arrow form is shorter, and when the body is one expression you can leave out return and the braces.
Method. Inside an object, add(a, b) { ... } is short for add: function (a, b) { ... }. You call it with the object in front: calculator.add(2, 3). All four print 5.
Example 2 — Treat a Function Like an Object
Ask a function about itself, and even give it a property of your own.
A function is a reusable block of code that you can run by calling its name with parentheses. It can take values (parameters) and send a result back with return. In JavaScript a function is also an object, so you can store it in a variable and pass it around.
A declaration starts with the word function and a name, and it can be called before the line where it is written. An arrow function is shorter, is usually stored in a const, and does not have its own this. Use arrow functions for short callbacks and declarations for the main functions.
For a regular function, this is the object the function was called on: user.greet() makes this equal to user. If you call the function on its own, this is lost. call(), apply() and bind() let you choose this by hand, and arrow functions use the this of the code around them.
call() and apply() run the function immediately; call() takes arguments one by one and apply() takes them in an array. bind() runs nothing and returns a new function with this fixed, which you call later.
A closure is an inner function that remembers the variables of the function it was created in, even after that outer function has finished. It is how a counter or a private setting can be kept without using a global variable.