After this lesson you can wrap a set of steps in a function, give it a name, and run it whenever you need it. You will also be able to read a function and say which part defines it and which part calls it.
Why functions exist
Imagine you want to print a greeting in five places in your program. You could copy the same lines five times. Then one day you want to change the wording, and you must find and edit all five copies. You will miss one.
A function solves this. You write the steps once, give them a name, and then run them by name. If the wording changes, you change it in one place.
Functions are also how you break a big problem into small pieces. A function called calculateTotal is much easier to understand than thirty lines of arithmetic sitting in the middle of a page.
Declaring and calling a function
The most common way to create a function is a function declaration:
function sayHello() {
console.log("Hello!");
}
sayHello();
sayHello();There are two separate ideas here.
- Defining the function: the
functionkeyword, the namesayHello, a pair of parentheses, and a body between curly braces. Defining does not run anything. It only teaches JavaScript whatsayHellomeans. - Calling the function:
sayHello();. The parentheses are what make it run. This code calls it twice, so it printsHello!twice.
Function names follow the same rules as variable names, and by convention they start with a lowercase letter and use camelCase, such as showMessage or calculateTotal. A good name is usually a verb, because a function does something.
Try it. The page below uses a small show helper that writes text into the result area, because the preview on this page does not display console.log output.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
function show(text) {
out.textContent += text + "\n";
}
function sayHello() {
show("Hello from a function!");
}
sayHello();
sayHello();
sayHello();
</script>Change the message, then add a fourth call. Every call runs the same body.
Passing information in
A function that always does exactly the same thing is of limited use. Most functions take parameters, which are placeholders for values supplied each time you call them:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Asha");
greet("Ben");Here name is the parameter. The values "Asha" and "Ben" are called arguments. Inside the function, name holds whichever argument was passed for that call. The next lesson, parameters, defaults and return values, goes deeper on this.
Getting a result out
Printing is not the same as producing a value. If you want to use the answer somewhere else, the function should return it:
function double(number) {
return number * 2;
}
const result = double(21);
console.log(result); // 42
console.log(double(5) + double(10)); // 30The return keyword does two things at once: it hands a value back to whoever called the function, and it stops the function immediately. Any lines after a return in the same path never run.
A call like double(21) is an expression. It turns into the value that was returned, so you can store it in a variable or use it inside bigger calculations.
If a function never reaches a return, its result is undefined:
function noResult() {
const x = 1 + 1;
}
console.log(noResult()); // undefinedA function is a value
In JavaScript a function is a thing you can refer to without running it. The name double on its own is the function itself. double(2) is the result of running it.
function double(number) {
return number * 2;
}
console.log(typeof double); // "function"
console.log(double(4)); // 8
const alias = double;
console.log(alias(10)); // 20Because functions are values, you can store them in variables, put them in arrays and pass them to other functions. That idea powers callbacks, which you will meet later in this section.
Functions can call other functions
Small functions become powerful when you combine them:
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
function show(text) {
out.textContent += text + "\n";
}
function addTax(price) {
return price * 1.2;
}
function formatPrice(price) {
return "$" + price.toFixed(2);
}
function priceWithTax(price) {
return formatPrice(addTax(price));
}
show(priceWithTax(10));
show(priceWithTax(99.5));
</script>Each function does one small job, and priceWithTax joins them. This makes each piece easy to test and easy to change. The tax rate of 1.2 here is only an example value for practice.
Common mistakes
Forgetting the parentheses. sayHello; is a valid line of code, but it does nothing visible. You need sayHello();. If a function seems not to run, check this first.
Using console.log instead of return. A function that only prints cannot give its answer to the rest of your code. If you write const total = add(2, 3) and add only prints, then total is undefined.
Code after return. Anything after a return on the same path is unreachable. Your editor may grey it out.
Defining but never calling. Writing a function does not run it. Beginners sometimes write a long function, refresh the page and wonder why nothing happens.
Giving two functions the same name. The later one silently replaces the earlier one. Choose distinct names.
Doing too much in one function. If you struggle to name it without using the word "and", split it into two functions.
Exercise
Write a function called describeRectangle that takes a width and a height and returns a string such as "A 4 by 3 rectangle has an area of 12.". Then call it twice with different numbers and show both results. As a stretch, write a second function area(width, height) that returns only the number, and make describeRectangle call it.
Next, learn how parameters, default values and return values work in detail in Parameters, defaults and return values.
Key points
- A function is a named block of code that you define once and run as many times as you like.
- A function declaration uses the function keyword, a name, parentheses and a body in curly braces.
- Writing the name alone does nothing; you run a function by adding parentheses after it.
- Information goes into a function through parameters and comes out through return.
- A function with no return statement gives back undefined.