Stats

Contributors: 2
2017-06-30
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

Arrow Function Example

Download node.js eBook

Example

Let's consider this example, that outputs the squares of the numbers 3, 5, and 7:

let nums = [3, 5, 7]
let squares = nums.map(function (n) {
  return n * n
})
console.log(squares)

Run in RunKit

The function passed to .map can also be written as arrow function by removing the function keyword and instead adding the arrow =>:

let nums = [3, 5, 7]
let squares = nums.map((n) => {
  return n * n
})
console.log(squares)

Run in RunKit

However, this can be written even more concise. If the function body consists of only one statement and that statement computes the return value, the curly braces of wrapping the function body can be removed, as well as the return keyword.

let nums = [3, 5, 7]
let squares = nums.map(n => n * n)
console.log(squares)

Run in RunKit