Mastering JavaScript Array Methods: A Beginner's Guide

Published: (March 3, 2026 at 02:33 PM EST)
7 min read
Source: Dev.to

Source: Dev.to

Introduction

Hello, fellow readers! Whether you’re just starting out with JavaScript arrays or brushing up on your skills, remember that arrays are the backbone of data handling in programming.

Think of an array as a bustling Indian street market: vendors line up in a row, each selling everything from vegetables and fish to spices and sweets. Each vendor (element) has a spot (index), and you can add, remove, or transform what’s on offer.

In a previous blog I covered the basics of arrays in JavaScript. In this post we’ll dive into some essential array methods:

  • push() / pop()
  • shift() / unshift()
  • forEach()
  • map()
  • reduce()
  • filter()

For each method you’ll get a short explanation, an easy‑to‑understand analogy, a before‑and‑after example, and a quick comparison with a traditional for loop. By the end you’ll have a hands‑on assignment to try out. Let’s get started—open your console and experiment as we go!


push() and pop()

Analogy – Imagine a family wedding buffet. push() is like adding a new guest to the end of the line, while pop() is like serving the last guest and removing them from the queue.

Example

// Before
let sweets = ['jalebi', 'gulab jamun', 'rasgulla'];

// push() – add 'peda' to the end
sweets.push('peda');
// After: ['jalebi', 'gulab jamun', 'rasgulla', 'peda']

// pop() – remove the last element
console.log(sweets.pop()); // 'peda'
// After: ['jalebi', 'gulab jamun', 'rasgulla']

Try this in your browser console or IDE. It’s that simple!


shift() and unshift()

Analogy – Think of the VIP line at a Bollywood movie premiere. unshift() adds a celebrity to the front of the line, while shift() removes the first person (the one who gets served first).

Example

// Before
let sweets = ['jalebi', 'gulab jamun', 'rasgulla'];

// unshift() – add 'barfi' at the beginning
sweets.unshift('barfi');
// After: ['barfi', 'jalebi', 'gulab jamun', 'rasgulla']

// shift() – remove the first element
sweets.shift();
// After: ['jalebi', 'gulab jamun', 'rasgulla']

These operations can be slower for large arrays because every element has to be re‑indexed, much like reorganising a crowded train compartment.


forEach()

Analogy – Announcing names at a school assembly: the function runs for each element, performing a side effect (e.g., logging) but never mutating the original array and returning undefined.

Example

let fruits = ['mango', 'banana', 'guava'];

fruits.forEach(fruit => console.log(`${fruit} is tasty!`));

Console output

mango is tasty!
banana is tasty!
guava is tasty!

The fruits array remains unchanged.

Important notes

  • You cannot break out of a forEach() loop except by throwing an exception.
  • forEach() expects a synchronous callback; it does not wait for promises.

map()

Analogy – A Diwali makeover for your array: map() walks through each item, transforms it, and returns a new array while leaving the original untouched. Imagine a group of friends getting “colored” for Holi; each friend’s excitement level is doubled.

Example

let prices = [10, 20, 30]; // street‑food prices in rupees

let doubled = prices.map(price => price * 2);

Result

  • New array (doubled): [20, 40, 60]
  • Original array (prices): [10, 20, 30]

Comparison – Traditional for loop vs. map()

// Using a for loop
let doubled = [];
for (let i = 0; i < prices.length; i++) {
  doubled.push(prices[i] * 2);
}

// Using map()
let doubled = prices.map(price => price * 2);

map() is cleaner, more declarative, and does not mutate the source array.

Caveat – In a sparse array, map() skips empty slots, preserving the sparseness in the returned array.


reduce()

Analogy – Tallying scores in a cricket match: starting with an initial accumulator (often 0), reduce() adds each player’s runs to produce a total.

Example

let runs = [50, 30, 20]; // runs scored by three batsmen

let total = runs.reduce((acc, run) => acc + run, 0);

Result: total is 100 (a single number, not an array).

reduce() can also concatenate strings, build objects, or perform any operation that collapses an array into a single value.

Note – The initial accumulator value does not have to be 0; it can be any type required by your logic.


filter()

Analogy – A bouncer at a wedding pandal: filter() lets only the invited guests (elements that satisfy a condition) pass through, returning a shallow copy of those elements.

Example

let ages = [15, 22, 18, 30]; // ages at a family gathering

let adults = ages.filter(age => age >= 18);

Result

  • New array (adults): [22, 18, 30]
  • Original array (ages): [15, 22, 18, 30]

Comparison – Traditional for loop vs. filter()

// Using a for loop
let adults = [];
for (let i = 0; i < ages.length; i++) {
  if (ages[i] >= 18) {
    adults.push(ages[i]);
  }
}

// Using filter()
let adults = ages.filter(age => age >= 18);

filter() removes the boilerplate, making the intent clear and the code more readable.


Practice Assignment

  1. Create an array of your favorite Indian dishes.
  2. Use push() to add a new dish, then pop() to remove it. Log the array after each step.
  3. Add two dishes to the front with unshift(), then remove the first one with shift(). Log the results.
  4. Log each dish with forEach().
  5. Create a new array of dish names in uppercase using map().
  6. Calculate the total number of characters across all dish names with reduce().
  7. Filter the dishes to keep only those whose names are longer than 6 characters.

Run your code in the console or an online editor and verify that each method behaves as described.

Happy coding! 🚀

Example: Using map(), filter(), and reduce()

// Original array
let numbers = [5, 8, 12, 15, 3];

// 1️⃣ Double each number
let doubled = numbers.map(num => num * 2);
// Expected: [10, 16, 24, 30, 6]

// 2️⃣ Keep only numbers greater than 10 (using the doubled array)
let greaterThan10 = doubled.filter(num => num > 10);
// Expected: [16, 24, 30]

// 3️⃣ Sum the remaining numbers
let sum = greaterThan10.reduce((acc, num) => acc + num, 0);
// Expected: 70

Tip: Run the code in your browser console or Node.js REPL. Feel free to modify the numbers array and observe how the results change. This hands‑on experimentation is the fastest way to master array methods.


Why These Methods Matter

  • push() / unshift() – simple ways to add elements.
  • map() – creates a new array by transforming each element.
  • filter() – creates a new array containing only elements that satisfy a condition.
  • reduce() – collapses an array into a single value (e.g., sum, product, object).

These built‑in functions keep your code concise and expressive—much like modern apps that simplify everyday tasks (ordering food, booking trains, etc.) for millions of users across India.


Next Steps

  1. Practice – try the above snippet with different arrays and conditions.
  2. Explore – look up other array helpers like some(), every(), find(), and flatMap().
  3. Ask – if anything is unclear, drop a question below.

Happy coding! 🚀

0 views
Back to Blog

Related posts

Read more »