JavaScript treats functions as first-class citizens. Functions are considered values similar to primitives.
Functions can be assigned to variables, passed as arguments to other functions and return a function from another function.
Power of higher-order functions
Allows for reusable code, reducing repetition
Abstract implementation details and promote modular code organization
Ideal for handling callbacks, enabling effective management of asynchronous operations and event-driven programming
Provides flexibility by allowing dynamic changes in behaviour through the use of different functions as arguments
Let's learn how higher-order functions for Arrays streamline coding workflow, allowing for more concise and reusable code.
forEach
forEach() method iterates over the content of the array and executes the callback function provides to it.
forEach simplifies array iteration, allowing you to perform actions on each element without the need for an explicit loop setup.
Constraints
forEach expects synchronous functions. Doesn't work on promises
Iterates over all the elements, cannot break in between except by throwing exceptions
map
map() method creates a new array by applying the callback function that transforms the elements in the original array.
filter
filter() method iterates over the original array and returns a shallow copy of the array with elements that match the condition provided in the callback function of the filter() method.
reduce
reduce() method iterates over the input array and returns a single value by performing operations provided in the reducer callback function on each element of the array.
The best example to understand this method is to iterate over an array to find the sum of all elements.
Here reduce() takes in two arguments: reducer() callback function and initial value (Optional). The reducer callback function is provided with these arguments.
accumulator (acc) - Value received from the previous callback function.
currentValue (num) - Value of the element at the current index
currentIndex - Index position of the element at any point in the iteration
For the first call, if an initial value is provided, it's taken for accumulator and the reduced callback function starts with the first element.
If an initial value is not provided, then the first element is taken for the accumulator and the reducer callback function starts from the second element
Constraints
- It throws an error for empty arrays. Caution must be exercised to avoid invoking it on empty arrays
sort
sort() method iterates over elements in the array and returns a reference to the same array sorted based on the callback function provided that acts as a comparison function
We need to ensure comparison functions follow these constraints for predictable sorting across all browsers.
- Pure and Stable function - Should not mutate original state and it must always return the same output for the same input