Skip to main content

Command Palette

Search for a command to run...

6 JavaScript Array Methods Explained

A practical guide to map, filter, reduce, forEach, push, and pop — with real examples, common mistakes, and hands-on exercises.

Updated
6 JavaScript Array Methods Explained
M

👋 Hey, I'm Mohd Kaif – a student documenting my journey through code. I write about what I'm learning in real-time – the wins, the struggles, and the "aha!" moments. From JavaScript and React to backend systems with Node.js, databases, DevOps, TypeScript, and AI integrations. This blog is my public learning journal: honest, evolving, and always exploring. If you're curious about any of these topics, let's learn and build together!

I used to think writing for loops everywhere was just "how JavaScript worked."

You need to double some numbers? Loop. Filter out certain items? Loop. Add everything up? Another loop. It felt normal — until I saw a senior developer write in one clean line what had taken me twelve lines to express.

That was the day I finally sat down and properly learned array methods. And honestly? It changed everything.

Does any of this sound familiar?

  • You write a for loop, and it works — but something about it feels clunky and hard to read back later

  • You know map() and filter() exist, but you're not quite sure when to use which one

  • You've heard of reduce() and quietly decided it's "too advanced" for now

  • You copy-paste loops from old projects because starting from scratch takes too long

The problem isn't your ability. Array methods just aren't taught with enough clarity. Once you see them explained with real, visual before-and-after examples, they click immediately.

This guide is for you.


✅ What You'll Learn

  • How push(), pop(), shift(), and unshift() manage your array's contents

  • How map() transforms every element into something new

  • How filter() selects only the items you actually want

  • How reduce() accumulates values — explained simply, without the usual confusion

  • How forEach() differs from map(), and when to use each

  • When not to use each method (common mistakes included)

No prerequisites required. If you know what an array is, you're ready.


A Quick Analogy Before We Start

Think of an array like a grocery bag. The methods below are just different ways to interact with what's inside it:

  • Some let you add or remove items

  • Some let you swap every item for something new

  • Some let you pull out only what you need

  • Some let you count or combine everything

Simple enough. Let's go.


1. push() and pop() — Add or Remove From the End

These two are your simplest tools. They work on the last position of the array.

push() — Add an item to the end

let fruits = ["apple", "banana"];

fruits.push("orange");

console.log(fruits);
// ["apple", "banana", "orange"]

Before: ["apple", "banana"]
After: ["apple", "banana", "orange"]


pop() — Remove the last item

let fruits = ["apple", "banana", "orange"];

fruits.pop();

console.log(fruits);
// ["apple", "banana"]

Before: ["apple", "banana", "orange"]
After: ["apple", "banana"]

💡 Note: Both push() and pop() modify the original array — they don't create a new one.


2. shift() and unshift() — Add or Remove From the Start

Same idea as push/pop, but these work on the first position instead.

unshift() — Add an item to the beginning

let fruits = ["banana", "orange"];

fruits.unshift("apple");

console.log(fruits);
// ["apple", "banana", "orange"]

Before: ["banana", "orange"]
After: ["apple", "banana", "orange"]


shift() — Remove the first item

let fruits = ["apple", "banana", "orange"];

fruits.shift();

console.log(fruits);
// ["banana", "orange"]

Before: ["apple", "banana", "orange"]
After: ["banana", "orange"]

A handy memory trick:

Method Position Action
push() End Add
pop() End Remove
unshift() Start Add
shift() Start Remove

3. map() — Transform Every Single Element

Here's where things get exciting.

map() takes your array, applies a function to every element, and returns a brand new array with the results. Your original array is left completely untouched.

Example: Double every number

let numbers = [1, 2, 3, 4];

let doubled = numbers.map(function(num) {
  return num * 2;
});

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

console.log(numbers);
// [1, 2, 3, 4]  ← original unchanged

Before: [1, 2, 3, 4]
After: [2, 4, 6, 8]


The Mental Model

map() says: "Go through every item, transform it, give me back the transformed version."

Picture a factory conveyor belt. Every item goes in one end, gets processed, and comes out the other end as something new. The original item isn't destroyed — you just get a new version of it.


For Loop vs. map() — Side by Side

The old way (for loop):

let doubled = [];

for (let i = 0; i < numbers.length; i++) {
  doubled.push(numbers[i] * 2);
}

The cleaner way (map):

let doubled = numbers.map(num => num * 2);

Same result. One line. Crystal clear intent.


🏋️ Try It Yourself

Open your browser console and run this:

let prices = [10, 25, 5, 50];

// Apply a 10% discount to every price
let discounted = prices.map(price => price * 0.9);

console.log(discounted);
// What do you get?

Try modifying the multiplier. Change 0.9 to 1.2 and see what happens. This is how real e-commerce discount logic works.


4. filter() — Keep Only What You Need

filter() goes through your array and returns a new array containing only the elements that pass a condition you define.

If the condition returns true → the item is kept.
If it returns false → the item is left out.

Example: Get numbers greater than 10

let numbers = [5, 12, 8, 20];

let result = numbers.filter(function(num) {
  return num > 10;
});

console.log(result);
// [12, 20]

Before: [5, 12, 8, 20]
After: [12, 20]


The Mental Model

filter() says: "Check each item against my rule — only let the ones that pass through."

Think of it like a bouncer at a door: every item in your array approaches, and the bouncer either lets it in or turns it away based on your condition.


A Real-World Example

let users = [
  { name: "Alice", isActive: true },
  { name: "Bob", isActive: false },
  { name: "Charlie", isActive: true },
];

let activeUsers = users.filter(user => user.isActive);

console.log(activeUsers);
// [{ name: "Alice", isActive: true }, { name: "Charlie", isActive: true }]

This exact pattern shows up in every real application — filtering products, users, notifications, you name it.


🏋️ Try It Yourself

let scores = [45, 72, 88, 34, 91, 60];

// Get only passing scores (70 and above)
let passing = scores.filter(score => score >= 70);

console.log(passing);
// [72, 88, 91]

Now try filtering for scores below 50. Can you do it in one line?


map() vs. filter() — Know Which to Use

This trips up a lot of beginners:

Goal Method
Change every item into something new map()
Remove items that don't meet a condition filter()

If you're transformingmap().
If you're selectingfilter().


5. reduce() — Combine Everything Into One Value

Let's be honest: reduce() has a scary reputation. The name doesn't help, and most explanations make it worse. But here's the truth — the concept is something you already understand.

Think of it like a running bank balance.

You start with $0 in your account. Every transaction adds to it. By the end, you have one final total. That's exactly what reduce() does.

Example: Sum all numbers

let numbers = [1, 2, 3, 4];

let total = numbers.reduce(function(accumulator, current) {
  return accumulator + current;
}, 0);

console.log(total);
// 10

Result: 10


Breaking It Down Step by Step

The two key pieces:

  • accumulator — the running total (your bank balance)

  • current — the item being processed right now (the transaction)

  • 0 — the starting value (your opening balance)

Step Accumulator Current New Total
1 0 1 1
2 1 2 3
3 3 3 6
4 6 4 10

Each step, the accumulator picks up where it left off — exactly like a running total.


🏋️ Try It Yourself

let cartItems = [
  { name: "T-shirt", price: 20 },
  { name: "Jeans", price: 50 },
  { name: "Shoes", price: 80 },
];

let cartTotal = cartItems.reduce((total, item) => total + item.price, 0);

console.log(cartTotal);
// 150

This is real shopping cart logic — used in real production apps.


6. forEach() — Loop Without Getting Anything Back

forEach() is the most straightforward of the group. It simply runs a function for each element — nothing more, nothing less. No new array. No return value.

Example: Log each number

let numbers = [1, 2, 3];

numbers.forEach(function(num) {
  console.log(num * 2);
});

// Output:
// 2
// 4
// 6

Use forEach() when you want to do something with each item but you don't need a new array back — like logging, updating the UI, or sending data somewhere.


The Big Difference: When to Use What

Method Returns? Use When...
map() ✅ New array You want to transform every element
filter() ✅ New array You want to keep only certain elements
reduce() ✅ Single value You want to combine everything into one
forEach() ❌ Nothing (undefined) You just want to do something per item

⚠️ Common Mistakes (That Are Easy to Fix)

Mistake 1: Expecting forEach() to return something

let result = numbers.forEach(num => num * 2);

console.log(result); // undefined ❌

forEach() is designed for side effects — it deliberately returns nothing. If you need the transformed values back, use map() instead.


Mistake 2: Forgetting return inside map()

// ❌ This gives you [undefined, undefined, undefined]
let doubled = numbers.map(num => {
  num * 2;  // No return!
});

// ✅ This works
let doubled = numbers.map(num => {
  return num * 2;
});

// ✅ Arrow function shorthand (no curly braces = implicit return)
let doubled = numbers.map(num => num * 2);

Mistake 3: Using map() when you need filter()

// ❌ Wrong — this uses map but doesn't actually remove anything
let result = numbers.map(num => {
  if (num > 10) return num;
});
// Gives you [undefined, 12, undefined, 20] — full of holes

// ✅ Correct — filter removes what doesn't pass
let result = numbers.filter(num => num > 10);
// Gives you [12, 20]

🎯 Final Assignment — Put It All Together

Open your browser console and work through this:

let numbers = [5, 10, 15, 20];

// 1. Double each number using map()
let doubled = numbers.map(num => num * 2);

// 2. Get only the numbers greater than 10 using filter()
let filtered = numbers.filter(num => num > 10);

// 3. Calculate the total sum using reduce()
let total = numbers.reduce((sum, num) => sum + num, 0);

console.log("Doubled:", doubled);   // [10, 20, 30, 40]
console.log("Filtered:", filtered); // [15, 20]
console.log("Total:", total);       // 50

Bonus challenge: Can you write a single expression that filters the numbers greater than 10, then doubles them?

let result = numbers
  .filter(num => num > 10)
  .map(num => num * 2);

console.log(result); // [30, 40]

That's the kind of readable, expressive code that makes other developers smile when they review your PRs.


What to Learn Next

You've now got the foundation. Here's a clear path to build on it:

  1. Chaining methods — Combine filter(), map(), and reduce() to process data in elegant pipelines. This is where real power unlocks.

  2. find() and findIndex() — Locate a specific item in an array without looping manually.

  3. some() and every() — Check whether any or all elements meet a condition. Incredibly useful for form validation and data checks.

  4. Working with arrays of objects — Most real-world data isn't [1, 2, 3]. Learn to filter users, sort products, and reduce shopping carts.

Master those four areas and you'll handle 95% of real-world array logic without breaking a sweat.


💬 Got Questions?

Drop a comment below! I'd love to hear where you got stuck, what clicked for you, or what real problem you're trying to solve.

Here are topics I'm covering in upcoming articles:

  • Chaining filter(), map(), and reduce(): How to combine these methods to build clean data pipelines in one expression

  • find(), findIndex(), some(), and every(): The four array methods most developers discover too late

  • Working with Arrays of Objects: Real-world patterns for filtering users, sorting products, and aggregating data

  • Common JavaScript Interview Questions on Arrays: The exact problems that show up in technical screens, solved and explained


Found this helpful? Share it with someone who's still writing for loops for everything — you might just change their week. And if you want more beginner-to-intermediate JavaScript breakdowns like this one, hit Follow so you don't miss the next one.

Zero to Full Stack Developer: From Basics to Production

Part 33 of 50

Complete full-stack web development series from zero to production. Learn HTML, CSS, JavaScript, TypeScript, React, Next.js, Node.js, databases, Docker, AWS, and AI integration. Build real-world projects step-by-step.

Up next

JavaScript Arrays for Beginners

Learn to store, access, update, and loop through data in JavaScript — no experience needed.