Higher Order Functions & JavaScript Array Methods
What does it mean by Higher Order Functions???
In programming, we often pass data like numbers, strings, or arrays into functions. Higher-Order Functions take this a step further, they can accept other functions as inputs or even return a function as their output. Essentially, they treat functions just like any other piece of data.
Without Higher Order Functions:
function doubleArray(arr) {
let results = [];
for (let num of arr) {
results.push(num * 2);
}
return results;
}
var res = doubleArray([1,2,3]);
console.log(res)
With HigherOrder Functions:
function doubleArray(arr, operation) {
let results = [];
for (let num of arr) {
results.push(operation(num)); //using that function that got passed
}
return results;
}
var res = doubleArray([1, 2, 3], (num) => num * 2);
console.log(res); // [2, 4, 6]
Explanation
Instead of writing a brand-new function every time you want to do something different to an array, you can just use a Higher-Order Function. It handles the boring part looping through the items and lets you just use whatever logic you need. This keeps your code super clean because you’re reusing the same loop for everything from doubling numbers to squaring them.
ArrayMethods:
1. .map()
The .map() method creates a new array by calling a provided function on every element of the original array.
How to use .map()?
//General usage of map
const numbers = [1, 2, 3, 4];
const doubled = numbers.map((num) => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8]
//Usage of map with all arguments
const result = numbers.map((element, index, array) => {
console.log("Element:", element);
console.log("Index:", index);
console.log("Original Array:", array);
return element * 2;
});
console.log(result);
The Callback Arguments
The callback function you pass into .map() can accept three arguments:
element: The current item being processed.index: The index of the current item.array: The original array.map()was called upon.
Does it mutate? No.
The Result: It returns a brand-new array and leaves the original one untouched.
2. .filter()
The .filter() method creates a new array with all elements that pass the test implemented by the provided function.
How to use .filter()?
// General usage of filter (get even numbers)
const numbers = [1, 2, 3, 4];
const evens = numbers.filter((num) => num % 2 === 0);
console.log(evens); // Output: [2, 4]
// Usage of filter with all arguments
const result = numbers.filter((element, index, array) => {
return element > 2;
});
console.log(result); // Output: [3, 4]
The Callback Arguments
element: The current item being processed.
index: The index of the current item.
array: The original array
.filter()was called upon.
Does it mutate? No.
Result: A new array containing only the elements that returned true.
3. .find()
The .find() method returns the value of the first element in the array that satisfies the provided testing function.
How to use .find()?
// General usage of find
const numbers = [1, 2, 3, 4];
const found = numbers.find((num) => num > 2);
console.log(found); // Output: 3
// Usage of find with all arguments
const result = numbers.find((element, index, array) => {
return index === 2;
});
console.log(result); // Output: 3
The Callback Arguments
element: The current item being processed.
index: The index of the current item.
array: The original array
.find()was called upon.
Does it mutate? No.
Result: The value of the first matching element found; otherwise, undefined.
4. .reduce()
The .reduce() method executes a reducer function on each element, resulting in a single output value.
How to use .reduce()?
// General usage of reduce (summing numbers)
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 10
// Usage of reduce with all arguments
const total = numbers.reduce((accumulator, element, index, array) => {
return accumulator + element;
}, 0);
The Callback Arguments
accumulator: The value resulting from the previous call (the "total so far").
element: The current item being processed.
index: The index of the current item.
array: The original array
.reduce()was called upon.
Does it mutate? No.
Result: A single value (number, string, object, etc.).
5. .every()
The .every() method tests whether all elements in the array pass the test implemented by the provided function.
How to use .every()?
// General usage of every
const numbers = [1, 2, 3, 4];
const allPositive = numbers.every((num) => num > 0);
console.log(allPositive); // Output: true
// Usage of every with all arguments
const result = numbers.every((element, index, array) => {
return element < 5;
});
The Callback Arguments
element: The current item being processed.
index: The index of the current item.
array: The original array
.every()was called upon.
Does it mutate? No. The Result: true if every element passes; otherwise, false.
6. .some()
The .some() method tests whether at least one element in the array passes the provided test.
How to use .some()?
// General usage of some
const numbers = [1, 2, 3, 4];
const hasLargeNum = numbers.some((num) => num > 3);
console.log(hasLargeNum); // Output: true
// Usage of some with all arguments
const result = numbers.some((element, index, array) => {
return index === 0 && element === 1;
});
The Callback Arguments
element: The current item being processed.
index: The index of the current item.
array: The original array
.some()was called upon.
Does it mutate? No.
Result: true if at least one element passes; otherwise, false.
7. .forEach()
The .forEach() method is used to execute a provided function once for every element in an array. It is commonly used to log data or perform "side effects" rather than transforming the array itself.
How to use .forEach()?
// General usage of forEach
const numbers = [1, 2, 3, 4];
numbers.forEach((num) => console.log(num * 2)); // Logs: 2, 4, 6, 8
// Usage of forEach with all arguments
numbers.forEach((element, index, array) => {
console.log(`Index ${index} in [${array}] is ${element}`);
});
The Callback Arguments
element: The current item being processed.
index: The index of the current item.
array: The original array
.forEach()was called upon.
Does it mutate? No.
Result: It returns undefined.
Utility Methods (Non-HOFs):
These are standard methods. They take data (numbers, strings) as arguments, not functions.
8. .splice()
The .splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
How to use .splice()?
const numbers = [1, 2, 3, 4];
numbers.splice(1, 2, 99); // Start at index 1, remove 2 items, add 99
console.log(numbers); // Output: [1, 99, 4]
The Arguments
start: The index at which to start changing the array.
deleteCount: The number of elements to remove.
items: The elements to add to the array (optional).
Does it mutate? Yes.
Result: An array containing the deleted elements.
9. .shift()
The .shift() method removes the first element from an array.
How to use .shift()?
// General usage of shift
const numbers = [1, 2, 3, 4];
const first = numbers.shift();
console.log(first); // Output: 1
console.log(numbers); // Output: [2, 3, 4]
The Arguments
- This method does not take any arguments.
Does it mutate? Yes**.**
Result: The element that was removed from the array.
13. .unshift()
The .unshift() method adds one or more elements to the beginning of an array.
How to use .unshift()?
// General usage of unshift
const numbers = [1, 2, 3, 4];
numbers.unshift(0);
console.log(numbers); // Output: [0, 1, 2, 3, 4]
The Arguments
- elements: The items to add to the front of the array.
Does it mutate? Yes**.**
Result: The new length of the array.
11. .reverse()
The .reverse() method reverses an array in place.
How to use .reverse()?
// General usage of reverse
const numbers = [1, 2, 3, 4];
numbers.reverse();
console.log(numbers); // Output: [4, 3, 2, 1]
The Arguments
- This method does not take any arguments.
Does it mutate? Yes**.**
Result: The original array, now reversed.
12. .includes()
The .includes() method determines whether an array includes a certain value among its entries.
How to use .includes()?
// General usage of includes
const numbers = [1, 2, 3, 4];
console.log(numbers.includes(3)); // Output: true
console.log(numbers.includes(10)); // Output: false
The Arguments
searchElement: The value to search for.
fromIndex: The position to start the search (optional).
Does it mutate? No.
Result: true if the value is found; otherwise, false.
13. .flat()
The .flat() method creates a new array with all sub-array elements concatenated into it recursively up to a specified depth.
How to use .flat()?
// General usage of flat
const nested = [1, [2, [3, 4]]];
console.log(nested.flat(1)); // Output: [1, 2, [3, 4]]
console.log(nested.flat(2)); // Output: [1, 2, 3, 4]
The Arguments
- depth: How deep the flat should go (default is 1).
Does it mutate? No.
Result: A brand-new flattened array.
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array