How to use arrow functions with Javascript filter

Javascript

Arrow functions were introduced in ES6. It is nothing more than a syntactically compact alternative to a regular function expression.

While previously regular function expressions were the only available option to write functions I believe arrow functions are easier to read and understand for certain cases, like the example below.

If the function has only one condition, and the condition returns a value, you can remove the {} curly braces and the return keyword.

Traditional javascript function:

const originalArray = [1, 2, 3, 4];

function filterNumber(number) {
    return number >= 3;
}
let newArray = originalArray.filter(filterNumber); // [ 3, 4 ]
console.log(newArray);

Simplified using arrow function:

const originalArray = [1, 2, 3, 4];

let newArray = originalArray.filter(number => number >= 3);
console.log(newArray); // [ 3, 4 ]

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Comments