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:
| Type | What happens | Like |
|---|---|---|
| Mutating | Changes the original array | Writing on the original marksheet ✍️ |
| Non-mutating | Gives you a new result, and the original stays the same | Writing 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?
| Method | Action | Position | Returns |
|---|---|---|---|
push(x) | Adds | End | The new length |
pop() | Removes | End | The removed item |
unshift(x) | Adds | Start | The new length |
shift() | Removes | Start | The removed item |
Real example: a ticket counter 🎫
Tip:
push()andpop()are faster thanunshift()andshift(), 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.
| Method | Changes 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 begindeleteCount→ how many items to removenewItems→ 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
| Point | slice(start, end) | splice(start, count, ...items) |
|---|---|---|
| Changes the original | ❌ No | ✅ Yes |
| Second number means | End index (not included) | How many to remove |
| Returns | The copied part | The 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. 🍊
filter→ From a basket of fruits, pick only the fresh ones.map→ Turn each fruit into a glass of juice.reduce→ Pour all the glasses into one jug to find the total.
| Method | What it does | Result |
|---|---|---|
map() | Changes every item | A new array of the same length |
filter() | Keeps only the items that pass a test | A new array, same or shorter |
reduce() | Combines all items | One 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:
| Round | acc (before) | price | New acc |
|---|---|---|---|
| Start | 0 | — | — |
| 1 | 0 | 499 | 499 |
| 2 | 499 | 1299 | 1798 |
| 3 | 1798 | 250 | 2048 ✅ |
Finding the highest score:
Counting votes (building an object):
⚠️ Always give a start value (like
0or{}). 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
| Point | forEach() | map() |
|---|---|---|
| Returns | undefined | A new array |
| Use when | You 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.
| Method | Returns | If nothing matches |
|---|---|---|
find() | The first matching item | undefined |
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? Usefilter().
Part 6: some and every
Imagine a school trip 🚌. Before leaving, the teacher asks two questions:
- "Has anyone forgotten their ID card?" → If even one student forgot, the answer is yes.
- "Has everyone paid the fees?" → The answer is yes only if all students paid.
| Method | Question it answers | Returns 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 (||): onetrueis enoughevery→ works like AND (&&): all must betrue
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
| Method | What it does | Returns | Changes the original? |
|---|---|---|---|
push(x) | Adds to the end | New length | ✅ Yes |
pop() | Removes from the end | Removed item | ✅ Yes |
unshift(x) | Adds to the start | New length | ✅ Yes |
shift() | Removes from the start | Removed item | ✅ Yes |
slice(s, e) | Copies a part | New array | ❌ No |
splice(s, n, ...x) | Removes / adds / replaces | Removed items | ✅ Yes |
map(fn) | Changes every item | New array (same length) | ❌ No |
filter(fn) | Keeps items that pass | New array | ❌ No |
reduce(fn, start) | Combines all items | One value | ❌ No |
find(fn) | First matching item | Item or undefined | ❌ No |
findIndex(fn) | Position of first match | Index or -1 | ❌ No |
some(fn) | At least one passes? | true / false | ❌ No |
every(fn) | All pass? | true / false | ❌ No |
Common Mistakes to Avoid
| Mistake | Problem | Fix |
|---|---|---|
Forgetting that push, splice, sort change the array | The original changes by mistake | Copy first with [...arr] |
Mixing up slice and splice | Wrong items removed or copied | slice = copy, splice = change |
Thinking slice(1, 3) includes index 3 | One item missing | The end index is not included |
Using forEach when you need a new array | Gets undefined | Use map() |
Forgetting the start value in reduce | Error on an empty array | Always pass a start value like 0 |
Using the result of find() without checking | Error if nothing matched | Check 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/popwork at the end, andunshift/shiftwork at the start of an array.slice()copies a part (safe), whilesplice()removes, adds, or replaces items (changes the original).map()changes every item,filter()keeps matching items, andreduce()combines everything into one value.find()/findIndex()return the first match, whilesome()/every()answer yes/no questions about the array.