Arrow functions
- Node.js course
- Beginner
- Lesson 73/116
- 5 min
Learn arrow function syntax with () => {}.
Arrow functions
An arrow function is a shorter way to write functions. It uses the => (arrow) token. It is common in one-line transformations and array methods.
There are two forms. The short single-parameter form: const sq = n => n * n;. With multiple parameters parentheses are required: const add = (a, b) => a + b;. With no parameters, empty parentheses: const pi = () => 3.14;.
A benefit of arrow functions is that short bodies need no return keyword. If you return a single expression, you can also drop the curly braces; the expression is returned automatically.
Implicit return
When an arrow function body is a single expression, you can drop the curly braces and the return keyword. This is called implicit return. The expression is returned automatically.
Example: const sq = n => n * n; and const sq = n => { return n * n; } mean the same. The first form is shorter and clearer; it is preferred for one-line transformations.
If you open curly braces, implicit return is off; you must write return. The form const sq = n => { n * n; } returns undefined because there is no return. This distinction is a common mistake.
Practice Square function
Define an arrow function named sq: const sq = (n) => n * n;. Print the result of sq(7) with console.log.
Starter code
// Define the sq arrow function and print the call resultSample solution
const sq = (n) => n * n;
console.log(sq(7));Expected output
49
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the arrow parts
| Term | Meaning |
|---|---|
(a, b) |
Parameter list |
=> |
Arrow token |
a + b |
Returned expression |
const add |
Binding name |
2 Which is a valid arrow function?
- const f = (a) => a * 2; Correct answer
- const f = function (a) => a * 2;
- function (a) => a * 2
- const f = (a) -> a * 2;
Explanation: (a) => a * 2 is a valid arrow function using implicit return.
3 Square a number
const sq = n => ____;
const sq = n => n * n;
Explanation: n => n * n squares and uses implicit return.