DEV Community

Cover image for JavaScript Array Methods You Must Know
Subhrangsu Bera
Subhrangsu Bera

Posted on

JavaScript Array Methods You Must Know

Welcome back! πŸ‘‹

In the previous post, we learned that an array is like a train holding your data in neat cars.

If you haven't read it yet, check it out here:

JavaScript Arrays 101 – The Ultimate Guide to Organizing Data

But a train isn't very useful if you can't:

  • add new cars
  • remove old ones
  • transform the cargo inside

JavaScript provides powerful array methods that help us work with data easily and efficiently.

In this guide, we’ll explore six essential array methods every developer should know.

Open your browser console (F12) and try the examples as you read.

1. The Dynamic Duo: push() and pop()

These methods work at the end of an array.

Think of them like adding or removing a trailer from the back of a truck.

push() β€” Add an element to the end

let cart = ["Milk", "Eggs"];

cart.push("Bread");

console.log(cart);
Enter fullscreen mode Exit fullscreen mode

Before

["Milk", "Eggs"]
Enter fullscreen mode Exit fullscreen mode

After push()

["Milk", "Eggs", "Bread"]
Enter fullscreen mode Exit fullscreen mode

pop() β€” Remove the last element

cart.pop();

console.log(cart);
Enter fullscreen mode Exit fullscreen mode

After pop()

["Milk", "Eggs"]
Enter fullscreen mode Exit fullscreen mode

2. The Front-Runners: shift() and unshift()

These methods work at the beginning of the array (index 0).

unshift()β€” Add an element to the start

let queue = ["Alice", "Bob"];

queue.unshift("Charlie");

console.log(queue);
Enter fullscreen mode Exit fullscreen mode

Before

["Alice", "Bob"]
Enter fullscreen mode Exit fullscreen mode

After unshift()

["Charlie", "Alice", "Bob"]
Enter fullscreen mode Exit fullscreen mode

shift() β€” Remove the first element

queue.shift();

console.log(queue);
Enter fullscreen mode Exit fullscreen mode

After shift()

["Alice", "Bob"]
Enter fullscreen mode Exit fullscreen mode

Everything moves forward when the first item is removed.

3. The Iterator: forEach()

forEach() runs a function for every element in an array.

It is commonly used when you just want to loop through items.

Traditional for Loop

let tasks = ["Clean", "Code", "Eat"];

for (let i = 0; i < tasks.length; i++) {
  console.log("Task:", tasks[i]);
}
Enter fullscreen mode Exit fullscreen mode

Using forEach()

tasks.forEach((task) => {
  console.log("Task:", task);
});
Enter fullscreen mode Exit fullscreen mode

Important note:

forEach() does not return a new array.
It is mainly used for side effects like logging, displaying data, or updating the UI.

4. The Transformer: map()

map() creates a new array by transforming each element of the original array.

It is commonly used when you want to modify every item.

Practical Example: Doubling Numbers

let numbers = [5, 10, 15];

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

console.log(doubled);
console.log(numbers);
Enter fullscreen mode Exit fullscreen mode

Original array

[5, 10, 15]
Enter fullscreen mode Exit fullscreen mode

After map()

[10, 20, 30]
Enter fullscreen mode Exit fullscreen mode

Array map method

Notice something important: The original array remains unchanged.

5. The Security Guard: filter()

filter() checks every item against a condition.

If the item passes the test, it goes into the new array.

Practical Example: Numbers Greater Than 10

let scores = [8, 12, 5, 20, 11];

let highScores = scores.filter(score => score > 10);

console.log(highScores);
Enter fullscreen mode Exit fullscreen mode

Original array

[8, 12, 5, 20, 11]
Enter fullscreen mode Exit fullscreen mode

Filtered result

[12, 20, 11]
Enter fullscreen mode Exit fullscreen mode

Array filter method
Again, the original array is not modified.

6. The Calculator: reduce()

reduce() takes an array and reduces it to a single value.

Think of it like a snowball rolling down a hill.
It starts small and gathers more snow as it moves.

Example: Sum of Numbers

let prices = [10, 20, 30];

let totalBill = prices.reduce((total, price) => {
  return total + price;
}, 0);

console.log(totalBill);
Enter fullscreen mode Exit fullscreen mode

Explanation step by step:

Start value = 0

Iteration 1 β†’ 0 + 10 = 10
Iteration 2 β†’ 10 + 20 = 30
Iteration 3 β†’ 30 + 30 = 60

Final result:

60
Enter fullscreen mode Exit fullscreen mode

Array reduce method

Note: Methods like map(), filter(), and reduce() are called higher-order array methods because they take functions as arguments.

Traditional Loop vs map() / filter()

Why use these methods instead of a regular loop?

Feature for loop map / filter
Readability More verbose Clean and expressive
Data mutation Can accidentally modify original array Returns a new array
Style Imperative programming Functional programming

Example comparison

Using for loop

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

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

Using map()

let doubled = numbers.map(num => num * 2);
Enter fullscreen mode Exit fullscreen mode

Much cleaner and easier to read.

Combined Example (Real Workflow)

Let's combine these methods together.

let numbers = [5, 10, 15, 20];

let doubled = numbers.map(num => num * 2);
// [10, 20, 30, 40]

let filtered = doubled.filter(num => num > 20);
// [30, 40]

let total = filtered.reduce((sum, num) => sum + num, 0);
// 70

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

Steps happening here:

1️⃣ Double each number

2️⃣ Keep numbers greater than 20

3️⃣ Calculate the final sum

Summary Cheat Sheet

Task Method
Add to end push()
Remove from end pop()
Add to start unshift()
Remove from start shift()
Loop through array forEach()
Transform items map()
Select specific items filter()
Calculate one value reduce()

Additional JavaScript Array Methods

1. find()

find() returns the first element that matches a condition.

let numbers = [5, 12, 8, 20];

let result = numbers.find(num => num > 10);

console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output

12
Enter fullscreen mode Exit fullscreen mode

Important points:

  • Returns only the first match
  • Returns undefined if nothing matches

2. findIndex()

Returns the index of the first matching element.

let numbers = [5, 12, 8, 20];

let index = numbers.findIndex(num => num > 10);

console.log(index);
Enter fullscreen mode Exit fullscreen mode

Output

1
Enter fullscreen mode Exit fullscreen mode

3. some()

Checks if at least one element passes a condition.

let numbers = [1, 3, 5, 8];

let hasEven = numbers.some(num => num % 2 === 0);

console.log(hasEven);
Enter fullscreen mode Exit fullscreen mode

Output

true
Enter fullscreen mode Exit fullscreen mode

4. every()

Checks if all elements satisfy a condition.

let numbers = [2, 4, 6, 8];

let allEven = numbers.every(num => num % 2 === 0);

console.log(allEven);
Enter fullscreen mode Exit fullscreen mode

Output

true
Enter fullscreen mode Exit fullscreen mode

5. includes()

Checks whether an array contains a specific value.

let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits.includes("Mango"));
Enter fullscreen mode Exit fullscreen mode

Output

true
Enter fullscreen mode Exit fullscreen mode

6. slice()

Creates a shallow copy of part of an array.

let numbers = [10, 20, 30, 40, 50];

let part = numbers.slice(1, 4);

console.log(part);
Enter fullscreen mode Exit fullscreen mode

Output

[20, 30, 40]
Enter fullscreen mode Exit fullscreen mode

Note:
The original array is not modified.

7. splice()

Used to add, remove, or replace elements in an array.

let fruits = ["Apple", "Banana", "Mango"];

fruits.splice(1, 1);

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Output

["Apple", "Mango"]
Enter fullscreen mode Exit fullscreen mode

Explanation

splice(startIndex, deleteCount)
Enter fullscreen mode Exit fullscreen mode

8. sort()

Sorts elements in an array.

let numbers = [40, 10, 100, 5];

numbers.sort((a, b) => a - b);

console.log(numbers);
Enter fullscreen mode Exit fullscreen mode

Output

[5, 10, 40, 100]
Enter fullscreen mode Exit fullscreen mode

9. join()

Converts an array into a string.

let words = ["Hello", "World"];

let sentence = words.join(" ");

console.log(sentence);
Enter fullscreen mode Exit fullscreen mode

Output

Hello World
Enter fullscreen mode Exit fullscreen mode

JavaScript Array Methods Return Chart

Method Returns Description Mutates Original?
push() New length of array Adds element(s) to the end YES
pop() Removed element Removes the last element YES
shift() Removed element Removes the first element YES
unshift() New length of array Adds element(s) to the start YES
splice() Array of removed elements Adds/removes items at any index YES
sort() Sorted array (same ref) Sorts elements in place YES
reverse() Reversed array (same ref) Reverses elements in place YES
fill() Modified array (same ref) Fills elements with a value YES
forEach() undefined Executes function for each element No
map() New array Transforms each element No
filter() New array Returns elements passing a condition No
slice() New array Returns a copy of a portion No
concat() New array Merges two or more arrays No
flat() New array Flattens nested arrays No
reduce() Single value Reduces array to one value No
find() Element or undefined Returns first matching element No
findIndex() Index or -1 Returns index of first match No
some() true / false Checks if any element passes No
every() true / false Checks if all elements pass No
includes() true / false Checks if value exists No
join() String Converts array to a string No

Quick Mental Model (Very Useful)

Returns a single value (or "Not an Array")

  • reduce() (Accumulator value)
  • find() (The element itself)
  • findIndex() (The index number)
  • indexOf() / lastIndexOf() (The index number)
  • join() (A string)

Returns a Boolean

  • some()
  • every()
  • includes()
  • Array.isArray()

Returns a New Array (Non-Mutating)

  • map()
  • filter()
  • slice()
  • concat()
  • flat()

Returns the Original Array (Mutated)

  • sort()
  • reverse()
  • fill()

Returns removed element(s)

  • pop() (Single item)
  • shift() (Single item)
  • splice() (Array of items)

Returns array length

  • push()
  • unshift()

Returns nothing useful

  • forEach() (Always undefined)

Practice Challenge

Open your browser console and try this exercise.

let numbers = [5, 10, 15, 20, 25];
Enter fullscreen mode Exit fullscreen mode

Step 1

Use map() to add 10 to each number

Step 2

Use filter() to keep numbers greater than 20

Step 3

Use reduce() to calculate the total sum

Experimenting in the console is one of the best ways to learn JavaScript.

If you're learning JavaScript, mastering these array methods will make your code cleaner, shorter, and more powerful.

Top comments (0)