Array Methods You Must Know

Search for a command to run...

No comments yet. Be the first to comment.
Introduction If you've ever built something with vanilla JavaScript and had to update the UI frequently, you already know the pain. You call document.getElementById, change some text, update a class,
Introduction If you've ever installed and tried out Linux after seeing a cool hacking sequence in a sci-fi movie, you know that opening it feels like stepping into a strange city with many roads named

Introduction Most JavaScript confusion around this comes from one wrong assumption: that this depends on where a function is defined. It doesn't. It depends on who called the function. That one shift

Introduction JavaScript gives you objects and arrays out of the box, and for a long time those two were the default answer to almost every data storage problem. Objects for key-value pairs, arrays for

Introduction Most JavaScript codebases are full of code like this: const user = { name: "Sara", age: 28, city: "Mumbai" }; const name = user.name; const age = user.age; const city = user.city; Three

Arrays are at the center of almost every JavaScript program. You filter data, transform lists, compute totals, add or remove items. Knowing the right method means writing 3 lines instead of 15. Here are the ones you'll use constantly.
push() and pop()These two are the simplest. push() adds an item to the end of an array. pop() removes the last item.
const fruits = ['apple', 'banana'];
fruits.push('mango');
// ['apple', 'banana', 'mango']
fruits.pop();
// ['apple', 'banana']
push() returns the new length of the array. pop() returns the item it removed. That returned value is easy to forget about but occasionally useful.
shift() and unshift()Same idea as push/pop, but at the front of the array instead of the end.
unshift() adds to the front. shift() removes from the front.
const queue = ['task1', 'task2'];
queue.unshift('task0');
// ['task0', 'task1', 'task2']
queue.shift();
// ['task1', 'task2']
A good way to remember: "shift" moves everything over (like shifting gears), while "unshift" pushes things back in at the start.
Worth noting: shift() and unshift() are slower than pop() and push() on large arrays because every element has to be re-indexed. For most code you'll write, it won't matter.
map()map() goes through every item in an array and returns a new array with each item transformed.
Say you have a list of prices and you want to apply a 10% discount to all of them. The traditional way:
const prices = [100, 200, 300];
const discounted = [];
for (let i = 0; i < prices.length; i++) {
discounted.push(prices[i] * 0.9);
}
// [90, 180, 270]
With map():
const prices = [100, 200, 300];
const discounted = prices.map(function(price) {
return price * 0.9;
});
// [90, 180, 270]
The original prices array stays untouched. map() always returns a brand-new array. That's important: use it when you want to transform data without modifying the source.
filter()filter() goes through each item and keeps only the ones that pass a condition. It returns a new array with the matching items.
Here's the for-loop version:
const scores = [45, 82, 91, 36, 67];
const passing = [];
for (let i = 0; i < scores.length; i++) {
if (scores[i] >= 60) {
passing.push(scores[i]);
}
}
// [82, 91, 67]
With filter():
const scores = [45, 82, 91, 36, 67];
const passing = scores.filter(function(score) {
return score >= 60;
});
// [82, 91, 67]
The callback returns true or false. If it returns true, the item gets included. If false, it gets dropped.
reduce()reduce() is the one that trips people up at first. The name is a bit abstract, but the idea is practical: you're collapsing an array down to a single value.
The simplest use case is a sum:
const numbers = [10, 20, 30, 40];
const total = numbers.reduce(function(accumulator, current) {
return accumulator + current;
}, 0);
// 100
Here's what's happening step by step:
Start with accumulator = 0 (that's the 0 at the end, called the initial value)
First round: 0 + 10 = 10
Second round: 10 + 20 = 30
Third round: 30 + 30 = 60
Fourth round: 60 + 40 = 100
The accumulator carries the running result. The current is the item being processed.
If you're not passing an initial value, reduce() uses the first element as the starting accumulator and begins from the second. That can cause bugs, so the habit of always providing an initial value is worth developing early.
forEach()forEach() runs a function on each item in the array. That's it. It doesn't return anything.
const names = ['Alice', 'Bob', 'Charlie'];
names.forEach(function(name) {
console.log('Hello, ' + name);
});
// Hello, Alice
// Hello, Bob
// Hello, Charlie
Where it gets confusing: people sometimes reach for forEach() when they should use map(). The difference is intent. If you want a new array back, use map(). If you're doing something as a side effect (logging, sending a request, updating the DOM), use forEach().
forEach() always returns undefined. Trying to assign its result to a variable and use it as an array is a common mistake.
| Method | Returns | Use when |
|---|---|---|
push() / pop() |
length or removed item | adding/removing at the end |
shift() / unshift() |
length or removed item | adding/removing at the front |
map() |
new array | transforming every item |
filter() |
new array | keeping items that match a condition |
reduce() |
single value | computing a total, building an object |
forEach() |
undefined |
side effects only |
Try using map() to build a list of HTML strings from an array of data. Use filter() to remove empty or invalid items from a form response. Use reduce() to count how many times each word appears in a sentence.
Once these six methods feel automatic, you'll find yourself writing smaller, cleaner code, and you'll also have the foundation to start combining them when needed.