Skip to main content

Command Palette

Search for a command to run...

JavaScript Array Methods – Practical Use Cases + Gotchas

Published
5 min read

1. push() and pop()

These work at the end of the array and modify the original array.


Normal Use Case

push() – Adding a new item to a cart

Before:

let cart = ["Shoes", "T-shirt"];
cart.push("Watch");

After:

["Shoes", "T-shirt", "Watch"]

pop() – Removing last added item

Before:

let cart = ["Shoes", "T-shirt", "Watch"];
cart.pop();

After:

["Shoes", "T-shirt"]

Gotchas

Gotcha 1: push() returns length, not array

let arr = [1, 2];
let result = arr.push(3);

console.log(result); // 3

//Updated the original array and stores it length in the variable

If you do:

arr = arr.push(4);//Now arr becomes a number with the length of array

console.log(arr)// output 4

Gotcha 2: They mutate original array

let a = [1, 2];
let b = a;

b.push(3);

console.log(a); 
// [1, 2, 3]

Both variables reference the same array.


2. shift() and unshift()

These work at the beginning of the array and also modify the original array.


Normal Use Case

shift() – Remove first notification

Before:

let notifications = ["Message1", "Message2", "Message3"];
notifications.shift();

After:

["Message2", "Message3"]

unshift() – Add urgent notification at start

Before:

let notifications = ["Message2", "Message3"];
notifications.unshift("Urgent Message");

After:

["Urgent Message", "Message2", "Message3"]

Gotchas

Gotcha 1: Slower for large arrays

Because every element must shift position internally.


Gotcha 2: Mutates original array

let a = [10, 20];
let b = a;

b.shift();

console.log(a); 
// [20]

3. map()

Used to transform every element. Returns a new array.


Normal Use Case

Convert prices from dollars to rupees

Before:

let prices = [10, 20, 30];
let inRupees = prices.map(price => price * 80);

After:

inRupees = [800, 1600, 2400]
prices = [10, 20, 30]

Original array remains unchanged.


Traditional for loop vs map()

Using for loop:

let result = [];
for (let i = 0; i < prices.length; i++) {
  result.push(prices[i] * 80);
}

Using map:

let result = prices.map(price => price * 80);

Cleaner and more readable.


Gotchas

Gotcha 1: Forgetting return

let numbers = [1, 2, 3];

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

console.log(doubled);
// [undefined, undefined, undefined]

Gotcha 2: map() does not remove elements

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

let result = numbers.map(num => {
  if (num > 2) return num;
});

console.log(result);
// [undefined, undefined, 3, 4]

Use filter() if you want to remove elements.


4. filter()

Used to select elements based on a condition. Returns a new array.


Normal Use Case

Get students who passed

Before:

let marks = [35, 80, 45, 90, 20];
let passed = marks.filter(mark => mark >= 40);

After:

passed = [80, 45, 90]
marks = [35, 80, 45, 90, 20]

Traditional for loop vs filter()

Using for loop:

let passed = [];
for (let i = 0; i < marks.length; i++) {
  if (marks[i] >= 40) {
    passed.push(marks[i]);
  }
}

Using filter:

let passed = marks.filter(mark => mark >= 40);

Cleaner and shorter.


Gotchas

Gotcha 1: Must return a boolean

let result = marks.filter(mark => {
  mark >= 40; // no return
});

Result:

[]

Because undefined is treated as false.


Gotcha 2: filter checks all elements

Even if first match is found, it keeps checking all items.


5. reduce()

Used to combine all elements into one value.


Normal Use Case

Calculate total bill amount

Before:

let bills = [100, 200, 300];
let total = bills.reduce((acc, current) => {
  return acc + current;
}, 0);

After:

total = 600

It starts from 0 and keeps adding each number.


Gotchas

Gotcha 1: No initial value

let numbers = [];
numbers.reduce((acc, num) => acc + num);

This throws an error.

Always pass initial value:

numbers.reduce((acc, num) => acc + num, 0);

Gotcha 2: Forgetting to return accumulator

let result = bills.reduce((acc, current) => {
  acc + current; 
}, 0);

This returns undefined.

You must return:

return acc + current;

6. forEach()

Runs a function for every element. Does not return anything.


Normal Use Case

Before:

let users = ["Arnab", "Riya", "Karan"];
users.forEach(user => {
  console.log(user);
});

Array remains unchanged.


Gotchas

Gotcha 1: forEach returns undefined

let result = users.forEach(user => user.toUpperCase());
console.log(result); // undefined

Use map() if you need a new array.


Gotcha 2: Cannot break

users.forEach(user => {
  if (user === "Riya") return;
  console.log(user);
});

This does not stop the loop. It only skips that iteration.

Use a traditional loop if you need break.


Final Summary

Mutates original array:

  • push()

  • pop()

  • shift()

  • unshift()

Does not mutate:

  • map()

  • filter()

  • reduce()

  • forEach()

More from this blog