DEV Community

Cover image for Array Methods You Must Know
SATYA SOOTAR
SATYA SOOTAR

Posted on

Array Methods You Must Know

Hello readers 👋, welcome to the 5th blog of this JavaScript series.

Today we're going to talk about something you'll use almost every day as a JavaScript developer - Array Methods.

Imagine you have a box of chocolates. You want to:

  • Add a new chocolate
  • Remove a chocolate
  • Double the number of chocolates
  • Find only the dark chocolates
  • Calculate the total price of all chocolates

In JavaScript, our "box of chocolates" is an array, and the actions we want to perform are array methods.

Let's dive in and learn these essential methods with simple, practical examples.

What are Array Methods?

Array methods are built-in functions in JavaScript that allow us to perform common operations on arrays easily. Instead of writing complex loops every time, we can use these methods to write cleaner, more readable code.

1. push() and pop() - Add and Remove from End

push() - Add item at the end

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Example:

let fruits = ["apple", "banana"];
console.log("Before push:", fruits); // ["apple", "banana"]

fruits.push("orange");
console.log("After push:", fruits);  // ["apple", "banana", "orange"]
console.log("New length:", fruits.length); // 3

// You can also add multiple items at once
fruits.push("mango", "grapes");
console.log("After adding multiple:", fruits); // ["apple", "banana", "orange", "mango", "grapes"]
Enter fullscreen mode Exit fullscreen mode

Real Life Example:

let shoppingCart = ["milk", "bread"];
console.log("Cart before:", shoppingCart); // ["milk", "bread"]

// You find eggs and add to cart
shoppingCart.push("eggs");
console.log("Cart after:", shoppingCart); // ["milk", "bread", "eggs"]
Enter fullscreen mode Exit fullscreen mode

pop() - Remove item from the end

The pop() method removes the last element from an array and returns that removed element.

Example:

let fruits = ["apple", "banana", "orange"];
console.log("Before pop:", fruits); // ["apple", "banana", "orange"]

let removedFruit = fruits.pop();
console.log("Removed fruit:", removedFruit); // "orange"
console.log("After pop:", fruits); // ["apple", "banana"]
Enter fullscreen mode Exit fullscreen mode

Real Life Example:

let playlist = ["Song A", "Song B", "Song C"];
console.log("Playlist before:", playlist); // ["Song A", "Song B", "Song C"]

// You finish listening to the last song
let finishedSong = playlist.pop();
console.log("Finished playing:", finishedSong); // "Song C"
console.log("Remaining playlist:", playlist); // ["Song A", "Song B"]
Enter fullscreen mode Exit fullscreen mode

2. shift() and unshift() - Add and Remove from Beginning

shift() - Remove item from the beginning

The shift() method removes the first element from an array and returns that removed element. All other elements shift down to lower indexes.

Example:

let queue = ["person1", "person2", "person3"];
console.log("Before shift:", queue); // ["person1", "person2", "person3"]

let servedPerson = queue.shift();
console.log("Served person:", servedPerson); // "person1"
console.log("After shift:", queue); // ["person2", "person3"]
Enter fullscreen mode Exit fullscreen mode

Real Life Example:

let ticketCounter = ["Raj", "Priya", "Amit"];
console.log("Queue before:", ticketCounter); // ["Raj", "Priya", "Amit"]

// First person gets their ticket and leaves
let firstPerson = ticketCounter.shift();
console.log("Serving:", firstPerson); // "Raj"
console.log("Queue now:", ticketCounter); // ["Priya", "Amit"]
Enter fullscreen mode Exit fullscreen mode

unshift() - Add item at the beginning

The unshift() method adds one or more elements to the beginning of an array and returns the new length.

Example:

let numbers = [2, 3, 4];
console.log("Before unshift:", numbers); // [2, 3, 4]

numbers.unshift(1);
console.log("After unshift:", numbers); // [1, 2, 3, 4]
console.log("New length:", numbers.length); // 4

// Add multiple items at the beginning
numbers.unshift(-1, 0);
console.log("After adding multiple:", numbers); // [-1, 0, 1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Real Life Example:

let priorityTasks = ["pay bills", "call mom"];
console.log("Tasks before:", priorityTasks); // ["pay bills", "call mom"]

// Emergency task comes up - must be done first
priorityTasks.unshift("emergency meeting");
console.log("Tasks after:", priorityTasks); // ["emergency meeting", "pay bills", "call mom"]
Enter fullscreen mode Exit fullscreen mode

Quick Comparison: push/pop vs shift/unshift

Method Where it works Returns Changes original array?
push() End New length Yes
pop() End Removed element Yes
shift() Beginning Removed element Yes
unshift() Beginning New length Yes

3. forEach() - Just Do Something With Each Item

The forEach() method executes a provided function once for each array element. It's like saying "for each item in this array, do this thing."

Think of it as a more elegant way to write a for loop.

Example:

let students = ["Raj", "Priya", "Amit"];

console.log("Calling attendance:");
students.forEach(function(student) {
  console.log(student + " is present");
});

// Output:
// Calling attendance:
// Raj is present
// Priya is present
// Amit is present
Enter fullscreen mode Exit fullscreen mode

Example:

let prices = [10, 20, 30];
console.log("Original prices:", prices); // [10, 20, 30]

// Let's just print each price with tax (we're not changing the array)
prices.forEach(function(price) {
  console.log("Price with tax: Rs.", price * 1.18);
});

// Original array remains the same
console.log("Original prices still:", prices); // [10, 20, 30]
Enter fullscreen mode Exit fullscreen mode

Real Life Example:

let shoppingList = ["milk", "eggs", "bread"];

console.log("Shopping Reminder:");
shoppingList.forEach(function(item, index) {
  console.log(`${index + 1}. Buy ${item}`);
});

// Output:
// Shopping Reminder:
// 1. Buy milk
// 2. Buy eggs
// 3. Buy bread
Enter fullscreen mode Exit fullscreen mode

Note: forEach() does NOT return a new array. It just performs an action on each item.

4. map() - Transform Each Item and Create a New Array

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Think of it as: Take each item, transform it, and put it in a new box.

Example:

let numbers = [1, 2, 3, 4];
console.log("Before map:", numbers); // [1, 2, 3, 4]

let doubledNumbers = numbers.map(function(number) {
  return number * 2;
});

console.log("After map:", numbers); // [1, 2, 3, 4] (original unchanged)
console.log("New doubled array:", doubledNumbers); // [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

Real Life Example:

let pricesInDollars = [10, 20, 30];
console.log("Prices in $:", pricesInDollars); // [10, 20, 30]

// Convert to rupees (assuming 1$ = ₹83)
let pricesInRupees = pricesInDollars.map(function(price) {
  return price * 83;
});

console.log("Prices in ₹:", pricesInRupees); // [830, 1660, 2490]
Enter fullscreen mode Exit fullscreen mode

basic map working

5. filter() - Get Only the Items That Meet a Condition

The filter() method creates a new array with all elements that pass a test (provided as a function).

Think of it as: Put each item through a sieve - only those that satisfy the condition go into the new array.

Example:

let numbers = [5, 12, 8, 130, 44];
console.log("Before filter:", numbers); // [5, 12, 8, 130, 44]

let largeNumbers = numbers.filter(function(number) {
  return number > 10;
});

console.log("After filter:", numbers); // [5, 12, 8, 130, 44] (original unchanged)
console.log("Numbers greater than 10:", largeNumbers); // [12, 130, 44]
Enter fullscreen mode Exit fullscreen mode

Real Life Example:

let ages = [12, 18, 25, 15, 30, 10];
console.log("All ages:", ages); // [12, 18, 25, 15, 30, 10]

// Find adults (age 18 and above)
let adults = ages.filter(function(age) {
  return age >= 18;
});

console.log("Adults:", adults); // [18, 25, 30]

// Find minors (age below 18)
let minors = ages.filter(function(age) {
  return age < 18;
});

console.log("Minors:", minors); // [12, 15, 10]
Enter fullscreen mode Exit fullscreen mode

Basic for each diagram

6. reduce() - Combine All Items Into a Single Value

The reduce() method executes a reducer function on each element of the array, resulting in a single output value.

Think of it as: Take all items and combine them into one thing (like adding all numbers, or joining all strings).

For beginners, think of it like this:

  • You have a pile of numbers
  • You want to add them all together
  • You start with 0, then add each number one by one

Example:

let numbers = [10, 20, 30, 40];
console.log("Numbers:", numbers); // [10, 20, 30, 40]

let total = numbers.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0); // Start with 0

console.log("Total sum:", total); // 100
Enter fullscreen mode Exit fullscreen mode

Let's see what happens step by step:

  • Start with accumulator = 0 (our starting point)
  • Add 10 → accumulator = 10
  • Add 20 → accumulator = 30
  • Add 30 → accumulator = 60
  • Add 40 → accumulator = 100
  • Final result = 100

Real Life Example:

let cartPrices = [299, 599, 199, 899];
console.log("Item prices:", cartPrices); // [299, 599, 199, 899]

// Calculate total bill
let totalBill = cartPrices.reduce(function(total, price) {
  return total + price;
}, 0);

console.log("Total bill: ₹", totalBill); // Total bill: ₹ 1996
Enter fullscreen mode Exit fullscreen mode

for Loop vs map/filter

Let's see how much cleaner map and filter make our code.

Example 1: Double each number

Using traditional for loop:

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

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

console.log(doubled); // [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

Using map:

let numbers = [1, 2, 3, 4];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

Example 2: Get numbers greater than 10

Using traditional for loop:

let numbers = [5, 12, 8, 130, 44];
let greaterThanTen = [];

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] > 10) {
    greaterThanTen.push(numbers[i]);
  }
}

console.log(greaterThanTen); // [12, 130, 44]
Enter fullscreen mode Exit fullscreen mode

Using filter:

let numbers = [5, 12, 8, 130, 44];
let greaterThanTen = numbers.filter(num => num > 10);
console.log(greaterThanTen); // [12, 130, 44]
Enter fullscreen mode Exit fullscreen mode

See how much cleaner and more readable the code becomes with array methods?

Important Tips for Beginners

  1. Try everything in the console - Open your browser's developer tools (F12) and test these methods yourself. See what happens!

  2. Don't chain methods initially - Write them step by step. Once you're comfortable, you can do things like:

   let result = numbers
     .filter(num => num > 10)
     .map(num => num * 2);
Enter fullscreen mode Exit fullscreen mode
  1. Remember what each method returns:

    • push/pop/shift/unshift → change original array
    • forEach → nothing (undefined), just performs action
    • map → new array of same length
    • filter → new array (may be shorter)
    • reduce → single value
  2. Original array remains unchanged for map, filter, and reduce - they create new arrays/values

Overview

Method What it does Returns Changes original?
push() Adds to end New length Yes
pop() Removes from end Removed element Yes
shift() Removes from start Removed element Yes
unshift() Adds to start New length Yes
forEach() Does something for each undefined No
map() Transforms each item New array No
filter() Keeps items that pass test New array No
reduce() Combines all items Single value No

Conclusion

Array methods are like special tools in your JavaScript toolbox. Instead of building everything from scratch with loops, you can use these methods to write cleaner, more readable code.

Remember:

  • push/pop and shift/unshift are for adding/removing items
  • forEach is for doing something with each item
  • map is for transforming each item into something new
  • filter is for picking only certain items
  • reduce is for combining everything into one value

The more you practice these, the more natural they'll become. Soon you'll find yourself reaching for these methods automatically instead of writing loops!

Pro tip: Keep your browser console open while coding and test each method as you learn. See what happens when you use them with different arrays.


Hope you liked this blog. If there's any mistake or something I can improve, do tell me. You can find me on LinkedIn and X, I post more stuff there.

Top comments (0)