Skip to main content

Command Palette

Search for a command to run...

Array Methods You Must Know in JavaScript

Updated
9 min read
Array Methods You Must Know in JavaScript
S
Software Engineer specializing in backend development and API architecture with 6+ years of experience. I build scalable web applications using PHP, REST/GraphQL APIs, and modern JavaScript, with strong expertise in WordPress, headless CMS solutions, and system integrations. Passionate about creating secure, high-performance systems that translate complex business needs into efficient technical solutions.

Arrays store lists of data. But storing is only half the job — you also need to add, remove, transform, and calculate from that data. JavaScript gives you powerful built-in methods to do all of this without writing complex loops from scratch.

Let's go through the most important ones, one at a time.


What is an Array? (Quick Recap)

An array is an ordered list of values:

const fruits = ["apple", "banana", "mango"];
const scores = [85, 92, 78, 95, 60];

Each item has an index starting from 0. Now let's see how to work with these lists.


1. push() and pop() — Adding and Removing from the End

push() — Add to the end

const cart = ["shirt", "shoes"];

cart.push("hat");

console.log(cart); // ["shirt", "shoes", "hat"]

You can push multiple items at once:

cart.push("belt", "socks");
console.log(cart); // ["shirt", "shoes", "hat", "belt", "socks"]

pop() — Remove from the end

const cart = ["shirt", "shoes", "hat"];

const removed = cart.pop();

console.log(removed); // "hat"
console.log(cart);    // ["shirt", "shoes"]

pop() returns the item it removed — useful if you need to know what was taken out.

Real use case: A browser history stack — push when you visit a page, pop when you hit back.


2. shift() and unshift() — Adding and Removing from the Front

unshift() — Add to the beginning

const queue = ["Rahul", "Priya"];

queue.unshift("Amit"); // Amit joins at the front

console.log(queue); // ["Amit", "Rahul", "Priya"]

shift() — Remove from the beginning

const queue = ["Amit", "Rahul", "Priya"];

const served = queue.shift(); // First person gets served

console.log(served); // "Amit"
console.log(queue);  // ["Rahul", "Priya"]

Real use case: A customer service queue — first in, first out.

push/pop vs shift/unshift at a glance:

Method Where Action
push() End Add
pop() End Remove
unshift() Beginning Add
shift() Beginning Remove

3. forEach() — Loop Through Every Item

forEach() runs a function on every element in the array. It's the clean alternative to a traditional for loop.

// Traditional for loop
const names = ["Rahul", "Priya", "Amit"];
for (let i = 0; i < names.length; i++) {
  console.log("Hello, " + names[i]);
}

// forEach — cleaner
names.forEach(name => {
  console.log("Hello, " + name);
});

// Output:
// Hello, Rahul
// Hello, Priya
// Hello, Amit

forEach() gives you the item, its index, and the full array if you need them:

const scores = [85, 92, 78];

scores.forEach((score, index) => {
  console.log(`Student \({index + 1}: \){score} marks`);
});

// Student 1: 85 marks
// Student 2: 92 marks
// Student 3: 78 marks

Note: forEach() always returns undefined. It's for side effects only — like logging or updating the DOM. If you need a new array back, use map().


4. map() — Transform Every Item

map() creates a brand new array by running a function on every element. The original array stays unchanged.

const prices = [100, 200, 300, 400];

// Add 18% GST to every price
const withGST = prices.map(price => price * 1.18);

console.log(prices);   // [100, 200, 300, 400]  ← original unchanged
console.log(withGST);  // [118, 236, 354, 472]  ← new array

Traditional loop vs map()

const numbers = [1, 2, 3, 4, 5];

// Old way — for loop
const doubled = [];
for (let i = 0; i < numbers.length; i++) {
  doubled.push(numbers[i] * 2);
}

// map() way — clean and readable
const doubled = numbers.map(n => n * 2);

console.log(doubled); // [2, 4, 6, 8, 10]

How map() works visually:

Input:   [1,    2,    3,    4,    5   ]
          ↓     ↓     ↓     ↓     ↓
Action: n * 2  n * 2  n * 2  n * 2  n * 2
          ↓     ↓     ↓     ↓     ↓
Output:  [2,    4,    6,    8,    10  ]

Every item goes in → gets transformed → comes out in a new array.

More practical examples:

// Extract names from an array of user objects
const users = [
  { name: "Rahul", age: 25 },
  { name: "Priya", age: 22 },
  { name: "Amit",  age: 28 }
];

const names = users.map(user => user.name);
console.log(names); // ["Rahul", "Priya", "Amit"]

// Convert celsius to fahrenheit
const celsius = [0, 20, 37, 100];
const fahrenheit = celsius.map(c => (c * 9/5) + 32);
console.log(fahrenheit); // [32, 68, 98.6, 212]

5. filter() — Keep Only What You Need

filter() creates a new array with only the items that pass a condition. Items that return false are left out.

const scores = [45, 82, 60, 91, 38, 74];

// Keep only passing scores (>= 60)
const passing = scores.filter(score => score >= 60);

console.log(passing); // [82, 60, 91, 74]

How filter() works visually:

Input:  [45,   82,   60,   91,   38,   74 ]
         ↓      ↓     ↓     ↓     ↓     ↓
Test:  >=60?  >=60?  >=60? >=60?  >=60?  >=60?
         ↓      ↓     ↓     ↓     ↓      ↓
       false  true  true  true  false   true
         ✗      ↓     ↓     ↓     ✗      ↓
Output:       [82,   60,   91,         74 ]

Only items where the test returns true make it into the new array.

Traditional loop vs filter()

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Old way
const evens = [];
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    evens.push(numbers[i]);
  }
}

// filter() way
const evens = numbers.filter(n => n % 2 === 0);

console.log(evens); // [2, 4, 6, 8, 10]

More practical examples:

// Filter products under ₹500
const products = [
  { name: "Pen",    price: 20  },
  { name: "Book",   price: 350 },
  { name: "Laptop", price: 45000 },
  { name: "Bag",    price: 499 }
];

const affordable = products.filter(p => p.price < 500);
console.log(affordable);
// [{ name: "Pen", price: 20 }, { name: "Book", price: 350 }, { name: "Bag", price: 499 }]

// Filter active users only
const users = [
  { name: "Rahul", active: true  },
  { name: "Priya", active: false },
  { name: "Amit",  active: true  }
];

const activeUsers = users.filter(user => user.active);
console.log(activeUsers);
// [{ name: "Rahul", active: true }, { name: "Amit", active: true }]

6. reduce() — Combine Everything into One Value

reduce() goes through every item in an array and accumulates them into a single result — a total, a string, an object, anything.

It takes two things:

  • A callback function with an accumulator and current value

  • An initial value for the accumulator

const numbers = [10, 20, 30, 40];

const total = numbers.reduce((accumulator, current) => {
  return accumulator + current;
}, 0); // 0 is the starting value

console.log(total); // 100

How reduce() works step by step:

Start: accumulator = 0

Step 1: acc(0)  + current(10) = 10
Step 2: acc(10) + current(20) = 30
Step 3: acc(30) + current(30) = 60
Step 4: acc(60) + current(40) = 100

Result: 100

Think of it like a running total — you start at 0, and with each item, you add to the total until you've gone through everything.

More examples:

// Find the highest score
const scores = [85, 92, 78, 95, 60];

const highest = scores.reduce((max, score) => {
  return score > max ? score : max;
}, 0);

console.log(highest); // 95

// Calculate total cart price
const cart = [
  { item: "Shirt", price: 799 },
  { item: "Shoes", price: 2499 },
  { item: "Belt",  price: 349 }
];

const cartTotal = cart.reduce((total, product) => {
  return total + product.price;
}, 0);

console.log(cartTotal); // 3647

Beginner tip: reduce() is the hardest of the three to grasp at first. Practice the sum example a few times. Once that clicks, everything else will too.


map() vs filter() vs reduce() — When to Use What

Method Returns Use when you want to
map() New array (same length) Transform every item
filter() New array (shorter) Keep only some items
reduce() Single value Combine all items into one result
forEach() undefined Do something with each item (no new array)

Quick Summary

const numbers = [5, 12, 3, 18, 7, 25];

// push & pop
numbers.push(30);       // add 30 to end
numbers.pop();          // remove last item

// shift & unshift
numbers.unshift(1);     // add 1 to front
numbers.shift();        // remove first item

// forEach — loop through
numbers.forEach(n => console.log(n));

// map — transform
const doubled = numbers.map(n => n * 2);
// [10, 24, 6, 36, 14, 50]

// filter — keep some
const bigOnes = numbers.filter(n => n > 10);
// [12, 18, 25]

// reduce — calculate total
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 70

🧪 Your Turn — Assignment Challenge

1. Create an array of numbers

const numbers = [3, 7, 15, 2, 22, 8, 18, 5];

2. Use map() to double each number

const doubled = numbers.map(n => n * 2);
console.log(doubled); // [6, 14, 30, 4, 44, 16, 36, 10]

3. Use filter() to get numbers greater than 10

const greaterThan10 = numbers.filter(n => n > 10);
console.log(greaterThan10); // [15, 22, 18]

4. Use reduce() to calculate total sum

const total = numbers.reduce((acc, n) => acc + n, 0);
console.log(total); // 80

Try changing the array values. Try filtering with different conditions. Try using map() before filter(). See what happens — that's how it all becomes second nature.


Wrapping Up

These six methods — push, pop, shift, unshift, map, filter, reduce, forEach — are the ones you'll use in almost every JavaScript project you ever build. From rendering lists in React to processing API data in Node.js, they show up everywhere.

Learn them well. Practice them in the console. They'll save you from writing dozens of manual for loops.

More from this blog