JavaScript arrays are an incredibly flexible way to model collections using techniques from functional programming. This article introduces you to using tools like forEach()
, map()
, and reduce()
for functional-style arrays.
Traditional JavaScript arrays
JavaScript’s arrays can hold heterogeneous types, change size on the fly, and readily insert or remove elements. Traditional methods like slice, splice, and push/pop do this by operating on the array itself, modifying the collection in a “destructive” way:
// Create an array with heterogeneous types:
let myArray = [10, "hello", true, { name: "Alice" }];
// Add to an array and change size on the fly:
myArray.push(42);
// Extract elements without modifying the original array:
let extracted = myArray.slice(1, 3);
Functional programming with arrays
Although JavaScript’s arrays are very capable out of the box, the functional paradigm improves the clarity and maintainability of array code. In general, functional programming looks to use functions as operators that can be passed into arrays. This allows for operating over the array like the head on a tape, rather than traditional imperative loops that describe in detail what is to occur.
To read this article in full, please click here