DEV Community

Cover image for Array Methods You Must Know
Pratham
Pratham

Posted on

Array Methods You Must Know

The six methods that turn JavaScript arrays from basic lists into powerful tools.


When I first learned arrays, I thought I was done. Create an array, access elements by index, loop through them with for — what else is there? Then I discovered array methods, and it felt like upgrading from a bicycle to a car.

Array methods are built-in functions that every array comes with. They let you add, remove, transform, filter, and reduce data — often in a single line of code. No manual loops, no index tracking, no off-by-one errors. Just tell the array what you want, and it handles the how.

In the ChaiCode Web Dev Cohort 2026, array methods came up almost immediately after we learned the basics. And honestly, these six methods cover probably 90% of what you'll ever do with arrays in real projects. Let's go through each one.


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

These two are the simplest array methods. They work on the end of the array.

push() — Add to the End

const fruits = ["Apple", "Mango"];
console.log(fruits); // ["Apple", "Mango"]

fruits.push("Banana");
console.log(fruits); // ["Apple", "Mango", "Banana"]

fruits.push("Grapes", "Orange"); // You can push multiple at once
console.log(fruits); // ["Apple", "Mango", "Banana", "Grapes", "Orange"]
Enter fullscreen mode Exit fullscreen mode

push() modifies the original array and returns the new length.

const newLength = fruits.push("Kiwi");
console.log(newLength); // 6
Enter fullscreen mode Exit fullscreen mode

pop() — Remove from the End

const fruits = ["Apple", "Mango", "Banana"];
console.log(fruits); // ["Apple", "Mango", "Banana"]

const removed = fruits.pop();
console.log(removed); // "Banana" — the removed element
console.log(fruits); // ["Apple", "Mango"] — Banana is gone
Enter fullscreen mode Exit fullscreen mode

pop() removes the last element, returns it, and shrinks the array by one.

Before and After

push("Banana"):
  Before: ["Apple", "Mango"]             → length: 2
  After:  ["Apple", "Mango", "Banana"]   → length: 3
                              ↑ added

pop():
  Before: ["Apple", "Mango", "Banana"]   → length: 3
  After:  ["Apple", "Mango"]             → length: 2
                              ↑ removed (returned "Banana")
Enter fullscreen mode Exit fullscreen mode

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

These work just like push() and pop(), but on the beginning of the array.

unshift() — Add to the Start

const tasks = ["Study", "Exercise"];
console.log(tasks); // ["Study", "Exercise"]

tasks.unshift("Wake up");
console.log(tasks); // ["Wake up", "Study", "Exercise"]
Enter fullscreen mode Exit fullscreen mode

shift() — Remove from the Start

const tasks = ["Wake up", "Study", "Exercise"];
console.log(tasks); // ["Wake up", "Study", "Exercise"]

const first = tasks.shift();
console.log(first); // "Wake up"
console.log(tasks); // ["Study", "Exercise"]
Enter fullscreen mode Exit fullscreen mode

Quick Reference: The Four Basic Methods

Method What It Does Position Modifies Original Returns
push() Adds element(s) End ✅ Yes New length
pop() Removes one element End ✅ Yes Removed element
unshift() Adds element(s) Start ✅ Yes New length
shift() Removes one element Start ✅ Yes Removed element

Think of it this way: push/pop work on the right side. unshift/shift work on the left side.


3. forEach() — Do Something with Each Element

forEach() is the simplest iteration method. It runs a function once for every element in the array. It's basically a cleaner replacement for a for loop when you just want to do something with each element (not transform or filter).

Traditional for Loop

const names = ["Pratham", "Arjun", "Priya"];

for (let i = 0; i < names.length; i++) {
  console.log(`Hello, ${names[i]}!`);
}
Enter fullscreen mode Exit fullscreen mode

Same Thing with forEach()

const names = ["Pratham", "Arjun", "Priya"];

names.forEach((name) => {
  console.log(`Hello, ${name}!`);
});
// Hello, Pratham!
// Hello, Arjun!
// Hello, Priya!
Enter fullscreen mode Exit fullscreen mode

No index tracking, no .length check, no i++. You just tell it what to do with each element.

The Callback Gets Three Arguments

const scores = [85, 92, 78];

scores.forEach((score, index, array) => {
  console.log(`Score ${index + 1}: ${score} (out of ${array.length} total)`);
});
// Score 1: 85 (out of 3 total)
// Score 2: 92 (out of 3 total)
// Score 3: 78 (out of 3 total)
Enter fullscreen mode Exit fullscreen mode

Most of the time you'll only use the first argument (the element). The index and full array are there if you need them.

Important: forEach() Returns Nothing

const result = [1, 2, 3].forEach((n) => n * 2);
console.log(result); // undefined
Enter fullscreen mode Exit fullscreen mode

forEach() is for side effects — logging, updating DOM elements, making API calls. If you need a new array back, use map().


4. map() — Transform Every Element

map() is one of the most important array methods you'll ever learn. It creates a new array by running a function on every element of the original array.

Think of it as: "Take each item, transform it, and give me back a new array of the results."

Example: Doubling Numbers

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

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

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

Traditional for Loop vs map()

// ❌ Traditional way — manual, more code
const numbers = [1, 2, 3, 4, 5];
const doubled = [];
for (let i = 0; i < numbers.length; i++) {
  doubled.push(numbers[i] * 2);
}

// ✅ With map() — one line, declarative
const doubled = numbers.map((num) => num * 2);
Enter fullscreen mode Exit fullscreen mode

Same result. But map() is shorter, doesn't require creating an empty array first, and clearly states its intent: "I'm transforming each element."

Flowchart: How map() Works

Original Array:    [1,    2,    3,    4,    5]
                    ↓     ↓     ↓     ↓     ↓
Callback:        num*2  num*2  num*2  num*2  num*2
                    ↓     ↓     ↓     ↓     ↓
New Array:         [2,    4,    6,    8,    10]

• Each element goes through the callback function
• Each result lands in the same position in the NEW array
• Original array is UNTOUCHED
Enter fullscreen mode Exit fullscreen mode

More Examples

// Convert names to uppercase
const names = ["pratham", "arjun", "priya"];
const uppercased = names.map((name) => name.toUpperCase());
console.log(uppercased); // ["PRATHAM", "ARJUN", "PRIYA"]

// Extract a property from objects
const users = [
  { name: "Pratham", age: 22 },
  { name: "Arjun", age: 21 },
  { name: "Priya", age: 23 },
];
const userNames = users.map((user) => user.name);
console.log(userNames); // ["Pratham", "Arjun", "Priya"]

// Add formatting
const prices = [100, 250, 500];
const formatted = prices.map((price) => `₹${price}.00`);
console.log(formatted); // ["₹100.00", "₹250.00", "₹500.00"]
Enter fullscreen mode Exit fullscreen mode

5. filter() — Keep Only What Matches

filter() creates a new array containing only the elements that pass a test (return true from the callback).

Think of it as: "Go through each item. Keep it if the condition is true. Throw it away if it's false."

Example: Get Even Numbers

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

const evens = numbers.filter((num) => num % 2 === 0);

console.log(evens); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, ..., 10] — original unchanged
Enter fullscreen mode Exit fullscreen mode

Flowchart: How filter() Works

Original Array:  [1,     2,     3,     4,     5,     6]
                  ↓      ↓      ↓      ↓      ↓      ↓
Test:           odd?   even?  odd?   even?  odd?   even?
                  ↓      ↓      ↓      ↓      ↓      ↓
Result:         false   true   false  true   false  true
                  ✗      ✓      ✗      ✓      ✗      ✓
                         ↓             ↓             ↓
New Array:             [ 2,            4,             6]

• Each element is tested by the callback
• true → element is KEPT in the new array
• false → element is EXCLUDED
• Original array is UNTOUCHED
Enter fullscreen mode Exit fullscreen mode

Traditional for Loop vs filter()

// ❌ Traditional way
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evens = [];
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    evens.push(numbers[i]);
  }
}

// ✅ With filter() — one line
const evens = numbers.filter((num) => num % 2 === 0);
Enter fullscreen mode Exit fullscreen mode

More Examples

// Filter adults
const ages = [15, 22, 17, 30, 12, 25, 8];
const adults = ages.filter((age) => age >= 18);
console.log(adults); // [22, 30, 25]

// Filter active users
const users = [
  { name: "Pratham", active: true },
  { name: "Arjun", active: false },
  { name: "Priya", active: true },
];
const activeUsers = users.filter((user) => user.active);
console.log(activeUsers);
// [{ name: "Pratham", active: true }, { name: "Priya", active: true }]

// Filter long strings
const words = ["hi", "hello", "hey", "greetings", "yo"];
const longWords = words.filter((word) => word.length > 3);
console.log(longWords); // ["hello", "greetings"]
Enter fullscreen mode Exit fullscreen mode

6. reduce() — Boil Everything Down to One Value

reduce() is the most powerful — and the most confusing at first — array method. It takes an entire array and reduces it down to a single value by accumulating a result as it goes through each element.

Think of it as a snowball rolling downhill, picking up snow as it goes. It starts small and gets bigger with each element it processes.

Basic Syntax

array.reduce((accumulator, currentValue) => {
  // do something
  return updatedAccumulator;
}, initialValue);
Enter fullscreen mode Exit fullscreen mode
  • accumulator — the running total (the snowball)
  • currentValue — the current element being processed
  • initialValue — what the accumulator starts as

Example: Sum of Numbers

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

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

console.log(total); // 100
Enter fullscreen mode Exit fullscreen mode

Visual: How reduce() Accumulates

Initial value: 0

Step 1:  sum = 0   + 10  →  10
Step 2:  sum = 10  + 20  →  30
Step 3:  sum = 30  + 30  →  60
Step 4:  sum = 60  + 40  →  100

Final result: 100

Think of it as:
[10, 20, 30, 40]  →  0 + 10 + 20 + 30 + 40  →  100
 entire array          accumulated step by step    one value
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Breakdown

Let me trace through each iteration so there's zero confusion:

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

const total = numbers.reduce((sum, num) => {
  console.log(`sum: ${sum}, num: ${num}, result: ${sum + num}`);
  return sum + num;
}, 0);

// sum: 0, num: 10, result: 10
// sum: 10, num: 20, result: 30
// sum: 30, num: 30, result: 60
// sum: 60, num: 40, result: 100

console.log(total); // 100
Enter fullscreen mode Exit fullscreen mode

Each time, the returned value becomes the new sum for the next iteration. The final returned value is the result.

More Examples

// Find the maximum value
const scores = [85, 92, 78, 95, 88];

const highest = scores.reduce((max, score) => (score > max ? score : max), 0);
console.log(highest); // 95

// Count occurrences
const votes = ["yes", "no", "yes", "yes", "no", "yes"];

const tally = votes.reduce((counts, vote) => {
  counts[vote] = (counts[vote] || 0) + 1;
  return counts;
}, {});
console.log(tally); // { yes: 4, no: 2 }
Enter fullscreen mode Exit fullscreen mode

Don't worry if reduce() feels tricky right now. It took me a few days of practice before I stopped needing to trace through every step manually. The key is to always ask: "What is the accumulator, and how does each element change it?"


map() vs filter() vs forEach() — When to Use Which

Method Returns Use When Modifies Original
forEach() undefined You want to do something (side effects) ❌ No
map() New array You want to transform each element ❌ No
filter() New array You want to keep elements that pass a test ❌ No
reduce() Single value You want to accumulate into one result ❌ No

Rule of thumb:

  • Need to log or update something? → forEach()
  • Need a new array of transformed values? → map()
  • Need a new array with some elements removed? → filter()
  • Need one final value from the whole array? → reduce()

Let's Practice: Hands-On Assignment

Part 1: Create an Array of Numbers

const numbers = [3, 7, 12, 5, 18, 22, 9, 15, 2, 30];
console.log("Original:", numbers);
// Original: [3, 7, 12, 5, 18, 22, 9, 15, 2, 30]
Enter fullscreen mode Exit fullscreen mode

Part 2: Use map() to Double Each Number

const doubled = numbers.map((num) => num * 2);
console.log("Doubled:", doubled);
// Doubled: [6, 14, 24, 10, 36, 44, 18, 30, 4, 60]
Enter fullscreen mode Exit fullscreen mode

Part 3: Use filter() to Get Numbers Greater Than 10

const greaterThanTen = numbers.filter((num) => num > 10);
console.log("Greater than 10:", greaterThanTen);
// Greater than 10: [12, 18, 22, 15, 30]
Enter fullscreen mode Exit fullscreen mode

Part 4: Use reduce() to Calculate Total Sum

const totalSum = numbers.reduce((sum, num) => sum + num, 0);
console.log("Total sum:", totalSum);
// Total sum: 123
Enter fullscreen mode Exit fullscreen mode

Part 5: Combine Them (Bonus)

// Double the numbers, keep only those above 20, then sum them
const result = numbers
  .map((num) => num * 2)
  .filter((num) => num > 20)
  .reduce((sum, num) => sum + num, 0);

console.log("Final result:", result);
// Doubled: [6, 14, 24, 10, 36, 44, 18, 30, 4, 60]
// Filtered (>20): [24, 36, 44, 30, 60]
// Sum: 194
Enter fullscreen mode Exit fullscreen mode

I know I said "avoid chaining initially" — but once you understand each method individually, seeing them chained together shows you why these methods are so powerful. Each one passes its result to the next.


Key Takeaways

  1. push()/pop() add and remove from the end. unshift()/shift() add and remove from the start. All four modify the original array.
  2. forEach() runs a function on each element for side effects. It returns nothing.
  3. map() transforms every element and returns a new array. The original stays unchanged.
  4. filter() tests every element and returns a new array with only the ones that passed. The original stays unchanged.
  5. reduce() accumulates the entire array into a single value. Start with the accumulator and initial value, and build up step by step.

Wrapping Up

These six methods are the workhorses of JavaScript. In real projects — whether you're building a to-do app, filtering search results, calculating cart totals, or rendering lists in React — you'll reach for map(), filter(), and reduce() constantly. The basic push(), pop(), shift(), and unshift() handle the simpler add/remove operations.

My advice: open your browser console right now and try every example in this article. Don't just read them — type them. Change the numbers. Break things. That's how these methods become second nature.

I'm learning all of this through the ChaiCode Web Dev Cohort 2026 under Hitesh Chaudhary and Piyush Garg, and array methods were the turning point where JavaScript started feeling genuinely fun. Once you can transform, filter, and reduce data in one line, you feel like you can build anything.

Connect with me on LinkedIn or visit PrathamDEV.in. More articles coming as the journey continues.

Happy coding! 🚀


Written by Pratham Bhardwaj | Web Dev Cohort 2026, ChaiCode

Top comments (0)