first class functions in JavaScript
Functions are first class citizens which mean they are treated like any other variable.
allows for the creation of higher-order functions
A higher-order function either takes one or more function as arguments or returns a function.
higher-order functions are awesome because it makes JavaScript easier to read.
As an example lets remove all shirts from an array of clothes.
using filter()
JavaScript
const clothes = ['shirt', 'sweater', 'pants', 'pants', 'sweater', 'shirt'];
const filteredClothes = clothes.filter(item => item !== 'shirt');
console.log(filteredClothes);
// (4) ["sweater", "pants", "pants", "sweater"]
without filter()
JavaScript
const clothes = ['shirt', 'sweater', 'pants', 'pants', 'sweater', 'shirt'];
const filteredClothes = [];
for (let i = 0; i < clothes.length; i++) {
if (clothes[i] !== 'shirt') {
filteredClothes.push(clothes[i]);
}
}
console.log(filteredClothes);
// (4) ["sweater", "pants", "pants", "sweater"]
Some other higher-order functions are map(), find() and reduce().