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)
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)
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)