Arrow Functions
JavaScript has one more, shorter way to write functions: arrow functions. You will meet them in almost every JavaScript program, and in the lesson on web pages you will use them yourself. Here is the same function written both ways. First the way you know:
function add(a, b) {
return a + b;
}And as an arrow function:
const add = (a, b) => a + b;Let's take the arrow function piece by piece:
const add =: an arrow function is written without a name, so we store it in a variable, and the function then goes by the variable's name. In JavaScript, a function is a value, just like numbers and text, so it can be stored in a variable. We useconst, because the variable will always hold the same function.(a, b): the parameters, in parentheses as usual.=>: the arrow, an equals sign followed by a greater-than sign. It separates the parameters from the body of the function.a + b: the body. When there are no curly braces after the arrow, the function returns the value after the arrow by itself, withoutreturn.
You call an arrow function like any other function:
const add = (a, b) => a + b;
console.log(add(2, 3));This prints:
5When a function needs several lines, put its body in curly braces, like in a function written with function. With curly braces, though, you have to write return yourself:
const rectangleArea = (width, height) => {
const area = width * height;
return area;
};
console.log(rectangleArea(4, 3));This prints:
12Notice the semicolon after the closing }. The whole function is the value of a variable created with const, and that statement ends with a semicolon, just like const price = 45;.
Watch out for two common mistakes:
- Curly braces without
return.const add = (a, b) => { a + b };calculates the sum, but doesn't return it, soadd(2, 3)givesundefined. - Calling the function above the line that creates it. Until that line runs, the variable
adddoesn't hold the function, so you get the errorReferenceError: Cannot access 'add' before initialization.
You may also come across an arrow function with one parameter written without the parentheses, such as number => number * 2. It means the same as (number) => number * 2.
Instructions
Below the function average, create an arrow function double with a parameter number that returns number * 2. Use the short form, without curly braces.
Rewrite the function average as an arrow function with a body in curly braces. Only its first line changes, to const average = (numbers) => {, and a semicolon goes after the closing }. The body stays as it is.
At the end of the program, print twice the average temperature: pass the result of average(temperatures) to the function double. The program prints 42.
Start programming for free
9/10