Skip to main content

Command Palette

Search for a command to run...

JavaScript Array Methods You Must Know

Updated
•11 min read•View as Markdown
JavaScript Array Methods You Must Know

When you start learning JavaScript, arrays quickly become one of the most commonly used data structures. Whether you are storing numbers, user data or results from an API, array appear everywhere.

JavaScript provides several n=built-in methods that make working with arrays much easier and cleaner compared to writing manual loops.

In this article, let us explore few of the essential array methods a developer must know.


1. The Basics: Adding & Removing (Stack/Queue)

push()

push() adds an element to the end of the array.

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

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

fruits.push('mango', 'grape');
console.log(fruits); // ['apple', 'banana', 'orange', 'mango', 'grape']

Before:

fruits: ['apple', 'banana']

After push('orange'):

fruits: ['apple', 'banana', 'orange']
                              ↑
                         Added here

Returns: The new length of the array.

let newLength = fruits.push('kiwi');
console.log(newLength); // 6

Use case: Building a list dynamically (e.g., adding items to a shopping cart).


pop() - Remove from End

What it does: Removes the last element from an array.

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

let removed = fruits.pop();
console.log(removed); // 'orange'
console.log(fruits);  // ['apple', 'banana']

Before:

fruits: ['apple', 'banana', 'orange']

After pop():

fruits: ['apple', 'banana']
                           X (removed)

Returns: The removed element.

Use case: Implementing a stack (Last In, First Out).


shift() - Remove from Beginning

What it does: Removes the first element from an array.

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

let removed = fruits.shift();
console.log(removed); // 'apple'
console.log(fruits);  // ['banana', 'orange']

Before:

fruits: ['apple', 'banana', 'orange']
         ↓
    Remove this

After shift():

fruits: ['banana', 'orange']

Returns: The removed element.

Use case: Implementing a queue (First In, First Out).


unshift() - Add to Beginning

What it does: Adds one or more elements to the beginning of an array.

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

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

fruits.unshift('mango', 'grape');
console.log(fruits); // ['mango', 'grape', 'apple', 'banana', 'orange']

Before:

fruits: ['banana', 'orange']

After unshift('apple'):

fruits: ['apple', 'banana', 'orange']
         ↑
    Added here

Returns: The new length of the array.

Use case: Adding priority items to the front of a list.


2. The Big Three: Transformation & Selection

map() — Transforming Arrays

What it does: Creates a new array by transforming each element with a function.

Syntax:

let newArray = array.map(function(element) {
  return transformedElement;
});

Example 1: Double Each Number

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

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

console.log(doubled); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5] (original unchanged)

Using arrow function (shorter):

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

Example 2: Extract Property from Objects

let users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

let names = users.map(user => user.name);
console.log(names); // ['Alice', 'Bob', 'Charlie']

For Loop vs map()

For loop:

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

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

map():

let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2);

Why map() is better:

  • Clear intent: "create new array by transforming each element"

  • No need to initialize empty array

  • No manual indexing

  • Easier to read and understand


Filtering Arrays: filter()

What it does: Creates a new array with elements that pass a test.

let newArray = array.filter(function(element) {
  return true; // or false
});

If the function returns true, the element is included. If false, it's excluded.

Example 1: Get Even Numbers

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

let evenNumbers = numbers.filter(function(num) {
  return num % 2 === 0;
});

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

Using arrow function:

let evenNumbers = numbers.filter(num => num % 2 === 0);

Example 2: Filter by Age

let users = [
  { name: 'Alice', age: 17 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 16 },
  { name: 'David', age: 30 }
];

let adults = users.filter(user => user.age >= 18);
console.log(adults);
// [
//   { name: 'Bob', age: 25 },
//   { name: 'David', age: 30 }
// ]

Example 3: Remove Empty Strings

let words = ['hello', '', 'world', '', 'javascript'];

let nonEmpty = words.filter(word => word !== '');
console.log(nonEmpty); // ['hello', 'world', 'javascript']

// Even shorter:
let nonEmpty = words.filter(word => word);

Accumulating Values: reduce()

What it does: Reduces an array to a single value by accumulating results.

This one is trickier, so let's start simple.

Think of reduce() like a snowball rolling down a hill:

  • It starts with an initial value (small snowball)

  • As it goes through each element, it accumulates (picks up snow)

  • At the end, you have one big snowball (final result)

Syntax:

let result = array.reduce(function(accumulator, currentValue) {
  return updatedAccumulator;
}, initialValue);
  • accumulator: The running total (the snowball)

  • currentValue: Current element being processed

  • initialValue: What to start with (usually 0 or empty array/object)

Example 1: Sum All Numbers

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

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

console.log(sum); // 15

Using arrow function:

let sum = numbers.reduce((total, num) => total + num, 0);

Step-by-Step: How reduce() Works

Array: [1, 2, 3, 4, 5]
Initial: 0

Step 1: total = 0,  num = 1  →  return 0 + 1  →  1
Step 2: total = 1,  num = 2  →  return 1 + 2  →  3
Step 3: total = 3,  num = 3  →  return 3 + 3  →  6
Step 4: total = 6,  num = 4  →  return 6 + 4  →  10
Step 5: total = 10, num = 5  →  return 10 + 5 →  15

Final result: 15

Example 2: Find Maximum

let numbers = [5, 12, 8, 3, 15, 7];

let max = numbers.reduce((largest, num) => {
  return num > largest ? num : largest;
}, numbers[0]);

console.log(max); // 15

Example 3: Count Occurrences

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

let count = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});

console.log(count);
// { apple: 3, banana: 2, orange: 1 }

Iterating Without Return: forEach()

What it does: Executes a function for each element, but doesn't return a new array.

Use when: You want to do something with each element but don't need a result.

Syntax:

array.forEach(function(element) {
  // Do something with element
});

Example 1: Log Each Element

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

fruits.forEach(function(fruit) {
  console.log(fruit);
});
// Output:
// apple
// banana
// orange

Using arrow function:

fruits.forEach(fruit => console.log(fruit));

Example 2: Update DOM Elements

let prices = [10, 20, 30, 40];

prices.forEach((price, index) => {
  console.log(`Item ${index + 1}: $${price}`);
});
// Output:
// Item 1: $10
// Item 2: $20
// Item 3: $30
// Item 4: $40

Example 3: Modify Objects in Array

let users = [
  { name: 'Alice', premium: false },
  { name: 'Bob', premium: false }
];

users.forEach(user => {
  user.premium = true; // Make everyone premium
});

console.log(users);
// [
//   { name: 'Alice', premium: true },
//   { name: 'Bob', premium: true }
// ]

forEach() vs map()

Key difference:

  • forEach(): Does something with each element, returns undefined

  • map(): Transforms each element, returns new array

let numbers = [1, 2, 3];

// forEach - no return value
let result1 = numbers.forEach(num => num * 2);
console.log(result1); // undefined

// map - returns new array
let result2 = numbers.map(num => num * 2);
console.log(result2); // [2, 4, 6]

Rule of thumb:

  • Use forEach() for side effects (logging, updating DOM, API calls)

  • Use map() when you need a new array


Quick Reference Table

Method Purpose Returns Mutates Original?
push() Add to end New length ✅ Yes
pop() Remove from end Removed element ✅ Yes
shift() Remove from start Removed element ✅ Yes
unshift() Add to start New length ✅ Yes
map() Transform each element New array ❌ No
filter() Keep matching elements New array ❌ No
reduce() Accumulate to single value Single value ❌ No
forEach() Execute function for each undefined Depends on function

Practice Assignment

Open your browser console and try this exercise.

Step 1

let numbers = [4,8,12,16,20];

Step 2 — Double numbers

numbers.map(n => n * 2)

Expected

[8,16,24,32,40]

Step 3 — Filter numbers > 10

numbers.filter(n => n > 10)

Expected

[12,16,20]

Step 4 — Calculate total sum

numbers.reduce((sum,n) => sum + n,0)

Expected

60

Complete Challenge: Combine Everything

Now let's combine multiple methods to solve a real problem:

let products = [
  { name: 'Laptop', price: 1000, inStock: true },
  { name: 'Phone', price: 500, inStock: false },
  { name: 'Tablet', price: 300, inStock: true },
  { name: 'Monitor', price: 200, inStock: true },
  { name: 'Keyboard', price: 50, inStock: false }
];

// Goal: Calculate total value of all in-stock products

// Step 1: Filter for in-stock products
let inStock = products.filter(product => product.inStock);

// Step 2: Extract prices using map
let prices = inStock.map(product => product.price);

// Step 3: Sum using reduce
let total = prices.reduce((sum, price) => sum + price, 0);

console.log(total); // 1500

Or in one chain (advanced):

let total = products
  .filter(product => product.inStock)
  .map(product => product.price)
  .reduce((sum, price) => sum + price, 0);

console.log(total); // 1500

Common Mistakes to Avoid

Mistake 1: Forgetting to Return in map()

// ❌ Wrong - no return statement
let doubled = numbers.map(num => {
  num * 2;
});
// Result: [undefined, undefined, undefined]

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

// ✅ Or shorter (implicit return)
let doubled = numbers.map(num => num * 2);

Mistake 2: Confusing forEach() and map()

// ❌ Wrong - forEach doesn't return array
let doubled = numbers.forEach(num => num * 2);
// Result: undefined

// ✅ Correct - use map
let doubled = numbers.map(num => num * 2);

Mistake 3: Mutating Original Array

let numbers = [1, 2, 3];

// ❌ Wrong - mutates original
numbers.forEach(num => num * 2); // Doesn't work anyway

// ✅ Correct - creates new array
let doubled = numbers.map(num => num * 2);
console.log(numbers); // [1, 2, 3] (unchanged)
console.log(doubled); // [2, 4, 6] (new array)

Mistake 4: Forgetting Initial Value in reduce()

// ❌ Risky - no initial value
let sum = numbers.reduce((total, num) => total + num);
// Works for numbers, but what if array is empty?

// ✅ Better - always provide initial value
let sum = numbers.reduce((total, num) => total + num, 0);

When to Use Which Method?

Need to...

Add/remove elements?
├─ At end?      → push() / pop()
└─ At start?    → unshift() / shift()

Create new array?
├─ Transform each element?     → map()
├─ Keep some elements?         → filter()
└─ Combine into single value?  → reduce()

Just iterate (no return)?
└─ Use forEach()

Final Thoughts

Learning array methods like:

  • push()

  • pop()

  • map()

  • filter()

  • reduce()

  • forEach()

will make your JavaScript code cleaner, more readable, and more professional.

Instead of writing long loops, you can express your logic in a modern declarative way.

The best way to learn them is simple:

👉 Open your browser console and experiment with arrays.