Array methods shorthand

Posted on July 2, 2020

JavaScript’s array methods pass their values through to the functions given to them. If you would only forward those to another function, you can skip the arrow function and name that function directly.

This works with Array.prototype.filter(), Array.prototype.map(), Array.prototype.every(), and more.

const numbers = [4, 8, 15, 16, 23, 42]
const isEven = n => n % 2 === 0
 
numbers.filter(number => isEven(number))  // ⇒ [4, 8, 16, 42]
numbers.filter(isEven)                    // ⇒ [4, 8, 16, 42]
 
numbers.map(number => isEven(number))     // ⇒ [true, true, false, true, false, true]
numbers.map(isEven)                       // ⇒ [true, true, false, true, false, true]
 
numbers.every(number => isEven(number))   // ⇒ false
numbers.every(isEven)                     // ⇒ false
const numbers = [4, 8, 15, 16, 23, 42]
const isEven = n => n % 2 === 0
 
numbers.filter(number => isEven(number))  // ⇒ [4, 8, 16, 42]
numbers.filter(isEven)                    // ⇒ [4, 8, 16, 42]
 
numbers.map(number => isEven(number))     // ⇒ [true, true, false, true, false, true]
numbers.map(isEven)                       // ⇒ [true, true, false, true, false, true]
 
numbers.every(number => isEven(number))   // ⇒ false
numbers.every(isEven)                     // ⇒ false

Continue reading

Read all snippets →