JavaScript Array Methods
Arrays are one of the most fundamental data structures in JavaScript. But their true power lies not just in storing data, but in the built-in methods that allow you to manipulate, traverse, and transform that data efficiently.
Mutating Methods: push, pop, shift, unshift
Methods like .push() and .pop() physically alter the array they are called on.
- push() adds to the end.
- pop() removes from the end.
- unshift() adds to the beginning.
- shift() removes from the beginning.
While fast and simple, overusing mutating methods in modern declarative UI frameworks (like React) can lead to bugs because the framework might not realize the underlying data has changed.
Transformation: map()
The .map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
const nums = [1, 2, 3]; const doubled = nums.map(x => x * 2); // doubled is [2, 4, 6] // nums is still [1, 2, 3]
Filtering: filter()
If you need to extract a subset of data, .filter() is your tool. It creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
Chaining Methods
Because map and filter return new array instances, you can chain them directly! This allows for incredibly readable data pipelines:
const items = [
{ name: 'Bike', price: 100 },
{ name: 'TV', price: 200 },
{ name: 'Album', price: 10 }
];
const expensiveItemNames = items
.filter(item => item.price > 50)
.map(item => item.name);
// Result: ['Bike', 'TV']View Bonus: reduce()+
The .reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element.
It is often used to sum all values in an array, or flatten nested arrays. It is the most powerful, but also the most complex array method to master.
