Array Methods

Think about a Swiss knife 🔪. It is one small tool, but it has a blade, scissors, a screwdriver, and a bottle opener. Each part does one special job.

JavaScript arrays are like that. Every array comes with many built-in methods, which are small tools that do special jobs like adding items, removing items, searching, or calculating totals.

In this lesson, you will learn the most useful ones. But first, one very important idea.


Part 1: Mutating vs Non-Mutating Methods

Imagine you have your original marksheet. 📄

  • Option 1: You write corrections directly on it with a pen. The original is changed forever. ✍️
  • Option 2: You take a photocopy and write on the copy. The original stays safe. 📑

Array methods work in the same two ways:

TypeWhat happensLike
MutatingChanges the original arrayWriting on the original marksheet ✍️
Non-mutatingGives you a new result, and the original stays the sameWriting on a photocopy 📑

A mutating method ✍️

A non-mutating method 📑

Which methods are which?

Mutating ✍️ (changes the original)Non-mutating 📑 (original stays safe)
push(), pop()slice()
shift(), unshift()map(), filter(), reduce()
splice()find(), findIndex()
sort(), reverse()some(), every()
includes(), indexOf(), concat()

Why does this matter?

If you change an array by mistake, other parts of your program that use the same array will also see the change. This causes bugs that are hard to find. 🐛

✅ Fix: Make a copy first with the spread operator [...array]:

Remember: Before using a mutating method, ask yourself: "Is it okay to change the original array?"


Part 2: push, pop, shift, and unshift

Picture a queue at a railway ticket counter. 🎫

  • A new person joins at the back → push()
  • The last person gets bored and leaves from the back → pop()
  • A senior citizen is allowed in at the front → unshift()
  • The person at the front gets a ticket and leaves → shift()
  unshift() ➕                        push() ➕
  shift()   ➖   [ Amit, Neha, Ravi ]  pop()  ➖
               START              END

All four are mutating methods. They change the original array.

push(): add to the end

pop(): remove from the end

unshift(): add to the start

shift(): remove from the start

What do they return?

MethodActionPositionReturns
push(x)AddsEndThe new length
pop()RemovesEndThe removed item
unshift(x)AddsStartThe new length
shift()RemovesStartThe removed item

Real example: a ticket counter 🎫

Tip: push() and pop() are faster than unshift() and shift(), because adding or removing at the start makes every other item move one place.


Part 3: slice and splice

These two names look almost the same, but they work very differently. 😅

Think of a pizza 🍕:

  • slice() → You take a photo of some slices. The pizza stays complete.
  • splice() → You actually cut out slices (and can even add new ones). The pizza is changed.
MethodChanges the original?Main job
slice()❌ No (non-mutating)Copy a part of the array
splice()✅ Yes (mutating)Remove, add, or replace items

Memory trick: splice has an extra "p", just like "p"ermanent. It permanently changes the array!

slice(start, end): copy a part

  • start → the index to begin from (included)
  • end → the index to stop before (not included)
days  = [ "Mon", "Tue", "Wed", "Thu", "Fri" ]
index:     0      1      2      3      4
slice(1, 4) → takes index 1, 2, 3 (stops BEFORE 4)

More ways to use slice():

Real example: top 3 on the leaderboard 🏆

splice(start, deleteCount, ...newItems): change the array

  • start → where to begin
  • deleteCount → how many items to remove
  • newItems → items to add at that position (optional)

It returns an array of the removed items.

1. Removing items

2. Adding items (remove 0)

3. Replacing items

Real example: cancelling an order 🧾

slice vs splice: side by side

Pointslice(start, end)splice(start, count, ...items)
Changes the original❌ No✅ Yes
Second number meansEnd index (not included)How many to remove
ReturnsThe copied partThe removed items
Can add items❌ No✅ Yes

Part 4: map, filter, and reduce

These three are the most powerful array methods. You will use them all the time! 💪

Imagine a fruit juice shop. 🍊

  1. filter → From a basket of fruits, pick only the fresh ones.
  2. map → Turn each fruit into a glass of juice.
  3. reduce → Pour all the glasses into one jug to find the total.
MethodWhat it doesResult
map()Changes every itemA new array of the same length
filter()Keeps only the items that pass a testA new array, same or shorter
reduce()Combines all itemsOne single value

All three are non-mutating. The original array stays safe. ✅

map(): change every item

map() runs a function on each item and puts the results in a new array.

The function also receives the index as the second value:

With objects: pick out just one detail

filter(): keep only what you need

filter() tests each item. If the test returns true, the item stays. If it returns false, the item is left out.

Real example: in-stock products under budget 🛍️

reduce(): combine everything into one value

reduce() goes through the array and builds up one result, like a piggy bank 🐷 collecting coins one by one.

array.reduce((accumulator, item) => newAccumulator, startValue);
  • accumulator (acc) → the running result (the piggy bank)
  • item → the current item
  • startValue → what the piggy bank starts with

How it works, step by step:

Roundacc (before)priceNew acc
Start0——
10499499
249912991798
317982502048 ✅

Finding the highest score:

Counting votes (building an object):

⚠️ Always give a start value (like 0 or {}). Without it, reduce() on an empty array throws an error.

Chaining: using all three together 🔗

Because map() and filter() return new arrays, you can connect them one after another.

Task: Find the total price of all in-stock items, after adding ₹100 delivery to each.

Read it like a story: "From the products, keep the in-stock ones, add delivery, then add everything up." 📖

map vs forEach

PointforEach()map()
ReturnsundefinedA new array
Use whenYou just want to do something (like print)You want to create a new array

Part 5: find and findIndex

You are at a railway platform looking for coach S4. 🚆 You walk along the train, and the moment you see S4, you stop and get in. You don't check the rest of the coaches.

find() and findIndex() work the same way. They search the array and stop at the first match.

MethodReturnsIf nothing matches
find()The first matching itemundefined
findIndex()The index of the first match-1

find(): get the first matching item

Even though 88 also matches, find() stops at the first one, which is 91.

Real example: finding a user by ID 👤

This is one of the most common uses in real apps.

When nothing matches, always check first:

findIndex(): get the position of the first match

Real example: updating an item in a cart 🛒

findIndex() is perfect when you want to change or remove an item.

find vs filter

Tip: Need one item? Use find(). Need all matching items? Use filter().


Part 6: some and every

Imagine a school trip 🚌. Before leaving, the teacher asks two questions:

  1. "Has anyone forgotten their ID card?" → If even one student forgot, the answer is yes.
  2. "Has everyone paid the fees?" → The answer is yes only if all students paid.
MethodQuestion it answersReturns true when
some()Does at least one item pass?Any one item passes
every()Do all items pass?Every item passes

Both always return true or false.

some(): is there at least one?

Real example: is any item out of stock? 📦

every(): do all items pass?

Real example: checking a form 📝

Side by side

Easy way to remember:

  • some → works like OR (||): one true is enough
  • every → works like AND (&&): all must be true

Both are fast, because they stop early once the answer is clear.

⚠️ A surprise with empty arrays

every() returns true because there is no item that fails. Keep this in mind when your array might be empty.


Quick Summary Table

MethodWhat it doesReturnsChanges the original?
push(x)Adds to the endNew length✅ Yes
pop()Removes from the endRemoved item✅ Yes
unshift(x)Adds to the startNew length✅ Yes
shift()Removes from the startRemoved item✅ Yes
slice(s, e)Copies a partNew array❌ No
splice(s, n, ...x)Removes / adds / replacesRemoved items✅ Yes
map(fn)Changes every itemNew array (same length)❌ No
filter(fn)Keeps items that passNew array❌ No
reduce(fn, start)Combines all itemsOne value❌ No
find(fn)First matching itemItem or undefined❌ No
findIndex(fn)Position of first matchIndex or -1❌ No
some(fn)At least one passes?true / false❌ No
every(fn)All pass?true / false❌ No

Common Mistakes to Avoid

MistakeProblemFix
Forgetting that push, splice, sort change the arrayThe original changes by mistakeCopy first with [...arr]
Mixing up slice and spliceWrong items removed or copiedslice = copy, splice = change
Thinking slice(1, 3) includes index 3One item missingThe end index is not included
Using forEach when you need a new arrayGets undefinedUse map()
Forgetting the start value in reduceError on an empty arrayAlways pass a start value like 0
Using the result of find() without checkingError if nothing matchedCheck if (item) first

Key Takeaways

  • Mutating methods (push, pop, shift, unshift, splice) change the original array. Non-mutating methods give you a new result.
  • push/pop work at the end, and unshift/shift work at the start of an array.
  • slice() copies a part (safe), while splice() removes, adds, or replaces items (changes the original).
  • map() changes every item, filter() keeps matching items, and reduce() combines everything into one value.
  • find()/findIndex() return the first match, while some()/every() answer yes/no questions about the array.