A function in JavaScript is a named, reusable piece of behaviour. You give it some arguments, and it gives you a value back. There are several ways to declare one, and they differ in ways that really matter. They differ in whether the name exists before the line runs, in whether the function can be called with new, and in what this means inside it.
This is the first lesson in the JavaScript Functions module, and the next lesson in this module is about "Parameters and Return Values".
How do I declare a function?
Two forms cover almost everything that you will write. A function declaration names the function and puts it in scope for the whole enclosing block. A function expression creates a function without a name of its own and assigns it to a variable.
// A declaration: the name is hoisted.
function greet(name) {
return 'Hello, ' + name + '!';
}
// An expression: the function has no name of its own.
const farewell = function (name) {
return 'Goodbye, ' + name + '!';
};
console.log('greet gives', greet('Ada'));
console.log('farewell gives', farewell('Ada'));
The difference in naming is not cosmetic. A declaration has a name that the engine knows about, so it shows up in stack traces and in the call stack of the debugger, and you can call it before the line where it is written. A function expression only has the name of the variable that holds it, and even that name is not visible inside the body of the function. That matters when you want a function to call itself.
Arrow functions are the third form, and they are the one that you will use most often. They get their own lesson later in this module, because the differences from a regular function are about behaviour and not only about syntax.
Why can I call a function before I define it?
Because function declarations are hoisted. The engine registers the name and the function before it runs a single statement of your file, so the call works even though the definition appears further down.
console.log('before the definition:', greet('Ada'));
function greet(name) {
return 'Hello, ' + name + '!';
}
// A function expression does not get the same treatment.
const farewell = function (name) {
return 'Goodbye, ' + name + '!';
};
console.log('type of farewell:', typeof farewell);
Hoisting applies to function declarations only. A function that is stored in a const is a binding that has not been given its value yet at that point in the file, so calling it earlier throws a ReferenceError. That is the same temporary dead zone that you met with let and const. The last line prints 'function' because by that point the assignment has already run.
This is not a licence to write your code out of order. Most style guides put declarations before their use anyway, because a reader who comes to a file from the top should not have to know that hoisting exists.
How do you call a function?
With parentheses. The name goes first, and then the arguments go inside the brackets.
function add(a, b) {
return a + b;
}
console.log('add(2, 3) gives', add(2, 3));
console.log('add(10, 5) gives', add(10, 5));
console.log('add("Total: ", 5) gives', add('Total: ', 5));
Notice that the function does not care what the arguments are. It adds them, and then the rules of JavaScript for + decide what that means. That is why add('Total: ', 5) produces a string. A function that behaves differently for numbers and for strings without being asked to is usually a sign that it needs a clearer contract, and the lesson about parameters and return values later in this module covers how to design one.
You can also call a function without using its result, and you can assign the result to a variable, and both of those are perfectly normal.
Can a function be a value?
Yes, and this is the idea that makes JavaScript functions genuinely different from the methods of older languages. A function is an object, so you can store it in a variable, put it in an array, pass it to another function, or return it from one.
const operations = {
add: function (a, b) {
return a + b;
},
multiply: function (a, b) {
return a * b;
},
};
function run(operation, a, b) {
return operation(a, b);
}
console.log('run add gives', run(operations.add, 2, 3));
console.log('run multiply gives', run(operations.multiply, 2, 3));
function double(number) {
return number * 2;
}
const doubled = [1, 2, 3].map(double);
console.log('doubled is', doubled);
The last few lines show the payoff. The function run does not know what it is being given. It simply calls whatever function arrives. That is why callbacks work, why array methods like map exist, and why event handlers can be swapped at runtime.
One consequence is worth knowing. A function declaration is also a value, so it can be reassigned just like any other variable.
What is an immediately invoked function expression?
It is a function expression wrapped in parentheses and then called straight away. It runs once and then disappears, and the variables inside it stay out of the surrounding code.
const result = (function () {
const secret = 'hidden inside';
return secret.toUpperCase();
})();
console.log('result is', result);
console.log('type of secret:', typeof secret);
Before ES modules existed, this was the standard way to stop the variables of a file from leaking into the global scope, and it still appears in plenty of older code. In modern JavaScript you do not usually need it. A const at the top level of a module is already scoped to that module.
The arrow-function version is shorter, and it is the form that you will see in most current code.
const result = (function () {
const secret = 'hidden inside';
return secret.toUpperCase();
})();
console.log('result is', result);
What happens when a function is a property of an object?
Then it is called a method, and the object that it belongs to is available inside the function as this. That is the only real difference between a function and a method. It is the same function value, called in a different way.
const cart = {
items: ['book', 'pen'],
count() {
return this.items.length;
},
};
console.log('cart.count() gives', cart.count());
const standalone = cart.count;
console.log('type of standalone:', typeof standalone);
Call it as cart.count() and this is the cart, so it returns 2. Pull the same function out into standalone and this is no longer the cart. Calling it that way usually throws, because there is no object for this to point at.
This is worth understanding now, even though arrow functions and this get their own lesson later, because it explains something that you have probably already seen. The line const standalone = cart.count followed by standalone() breaks in a way that looks mysterious. It is not mysterious at all. The function was never attached to the object. Only the call was.
The function rules worth remembering
- A declaration is hoisted and can be called before it is written. A function expression that is stored in a
constcannot. - Give a function expression a name when you will need to call the function from inside itself.
- Functions are values, so you can store them, pass them, and return them.
- A method is simply a function that is called as a property of an object, and that is what makes
thisavailable inside it. - An immediately invoked function expression runs once and keeps its variables private, although ES modules make it unnecessary in new code.
Try it yourself: write a function formatOrder(order) that returns a summary string, and then write the same logic in three different ways. Make it a declaration, then make it a function expression, and then make it an arrow function. Pass each one to a helper that calls it with a sample order. Then convert one of them into a method on an order object and call it both as order.formatOrder() and as a detached function, and note exactly where the second version stops working.