Array Methods You Must Know
When I first started learning JavaScript, arrays looked simple. Just a list of values, right?
But soon I realized arrays are much more powerful. Instead of writing long loops every time, JavaScript gives us built-in methods that make our work easier and cleaner.
In this article, I’ll explain some must-know array methods in the simplest way possible — just like I wish someone explained them to me when I started.
1. push() and pop()
Think of an array like a stack of books.
You can add a book on top or remove the top book.
That’s exactly how push() and pop() work.
push() – Adds an element to the end
Example:
let fruits = ["Apple", "Banana"];
fruits.push("Mango");
console.log(fruits);
Before
["Apple", "Banana"]
After
["Apple", "Banana", "Mango"]
2. shift() and unshift()
Now imagine a line of people waiting for a bus.
The first person in line leaves first.
shift() – Removes the first element
let numbers = [1, 2, 3];
numbers.shift();
console.log(numbers);
Before
[1,2,3]
After
[2,3]
unshift() – Adds an element to the beginning
let numbers = [2,3];
numbers.unshift(1);
console.log(numbers);
Before
[2,3]
After
[1,2,3]
3. map()
Now comes one of the most useful array methods.
Imagine you have a list of numbers and you want to double every number.
Instead of writing a long loop, we can use map().
Example
let numbers = [2,4,6];
let doubled = numbers.map(function(num){
return num * 2;
});
console.log(doubled);
Result
[4,8,12]
Traditional loop vs map()
Using for loop
let numbers = [2,4,6];
let result = [];
for(let i=0;i<numbers.length;i++){
result.push(numbers[i] * 2);
}
Using map
let result = numbers.map(num => num * 2);
You can see map() is shorter and cleaner.
4. filter()
Now imagine you have a list of numbers and you want only numbers greater than 10.
That’s where filter() comes in.
Example
let numbers = [5,12,8,20];
let greaterThanTen = numbers.filter(function(num){
return num > 10;
});
console.log(greaterThanTen);
Result
[12,20]
5. reduce() (Beginner Explanation)
reduce() sounds scary at first, but the idea is simple.
It combines all array values into a single value.
For example: calculating the total sum.
Example
let numbers = [5,10,15];
let total = numbers.reduce(function(accumulator, current){
return accumulator + current;
},0);
console.log(total);
Step by Step
0 + 5 = 5
5 + 10 = 15
15 + 15 = 30
Final result:
30
Mini Assignment (Try This Yourself)
Now open your browser console and try this:
let numbers = [5,10,15,20];
let doubled = numbers.map(num => num * 2);
let greaterThanTen = numbers.filter(num => num > 10);
let total = numbers.reduce((sum,num)=> sum + num,0);
console.log(doubled);
console.log(greaterThanTen);
console.log(total);
When you start learning JavaScript, loops feel like the only option. But once you discover array methods like push, pop, map, filter, and reduce, coding becomes much cleaner and more enjoyable.