A list of products, a student's marks, the latest notifications: all of these can live in JavaScript arrays. Array methods help you add items, find what you need, change values, and calculate totals.
Many methods look similar at first. The easiest way to understand them is to ask two questions. What does this method return? Does it change the original array? We will answer both as we work through some everyday methods.
Start with the array and the return value
Most examples use [3, 4, 5, 6]. Each code block starts fresh, so a change in one example does not affect the next. JavaScript arrays use zero-based positions: 3 is at index 0, 4 is at index 1, and 6 is at index 3.
A method call produces a return value. Some calls also change the array. For example, push(7) returns the new length, 5, while the array becomes [3, 4, 5, 6, 7]. These are two different things to keep track of.
In callbacks such as (num) => num > 4, num is the current item and the expression after the arrow is the returned result. A condition is considered passed when the callback returns a truthy value. Our conditions return true or false.
1. pop() — Remove the last item
Use pop() when you need to remove the final item and use that item elsewhere. It changes the array and returns the removed value. For an empty array, it returns undefined.
const numbers = [3, 4, 5, 6];
const removed = numbers.pop();
console.log(removed); // 6
console.log(numbers); // [3, 4, 5]An undo feature can pop the most recent action from a list.
2. push() — Add items at the end
push() adds one or more items to the end. It changes the array and returns its new length.
const numbers = [3, 4, 5, 6];
const newLength = numbers.push(7);
console.log(newLength); // 5
console.log(numbers); // [3, 4, 5, 6, 7]You can push a new message into a local list of messages.
3. reverse() — Reverse the order
reverse() puts the items in the opposite order. It changes the original array and returns a reference to that same array.
const numbers = [3, 4, 5, 6];
const reversed = numbers.reverse();
console.log(reversed); // [6, 5, 4, 3]
console.log(numbers); // [6, 5, 4, 3]
console.log(reversed === numbers); // trueFor a separate reversed array, use [...numbers].reverse(). This copies the outer array first. Current environments also provide toReversed().
4. map() — Transform each item
map() builds a new array from the values your callback returns. In this example, num is the current number. The callback adds 6 to it.
const numbers = [3, 4, 5, 6];
const increased = numbers.map((num) => num + 6);
console.log(increased); // [9, 10, 11, 12]
console.log(numbers); // [3, 4, 5, 6]Use map() to turn a list of user objects into a list of names. The method itself leaves the original array unchanged, but a callback can still modify objects it receives.
5. find() — Get the first matching item
find() checks items from the beginning and returns the first value that passes your condition. It returns undefined when there is no match.
const numbers = [3, 4, 5, 6];
console.log(numbers.find((num) => num > 4)); // 5
console.log(numbers.find((num) => num > 10)); // undefinedUse find() to get one product by its ID. If several items match, you get the first one.
6. at() — Read an item by its position
Array positions start at zero. at(1) reads the second item. Negative positions count backwards from the end, so at(-1) reads the last item.
const numbers = [3, 4, 5, 6];
console.log(numbers.at(1)); // 4
console.log(numbers.at(-1)); // 6
console.log(numbers.at(10)); // undefinedUse at(-1) to read the last message while keeping the array unchanged.
7. fill() — Replace values
fill() writes the same value into part or all of an array. It changes the original array and returns that same array. The optional start position is included and the end position is excluded.
const numbers = [3, 4, 5, 6];
console.log(numbers.fill(1)); // [1, 1, 1, 1]
console.log(numbers); // [1, 1, 1, 1]
const partial = [3, 4, 5, 6];
console.log(partial.fill(0, 1, 3)); // [3, 0, 0, 6]Be careful when filling with an object. Each filled position receives a reference to the same object.
8. join() — Turn items into a string
join() combines the items into one string, with your separator between them. It leaves the array unchanged. An empty array produces an empty string.
const numbers = [3, 4, 5, 6];
console.log(numbers.join("-")); // "3-4-5-6"
console.log(numbers.join(", ")); // "3, 4, 5, 6"Use join(", ") to display a list of selected skills as readable text.
9. shift() — Remove the first item
shift() removes the first item, moves the remaining items towards the beginning, and returns the removed value. It changes the array. An empty array returns undefined.
const numbers = [3, 4, 5, 6];
const removed = numbers.shift();
console.log(removed); // 3
console.log(numbers); // [4, 5, 6]A small queue can use shift() to take the next item from its front.
10. unshift() — Add items at the beginning
unshift() adds one or more items at the start. It changes the array and returns its new length.
const numbers = [3, 4, 5, 6];
const newLength = numbers.unshift(1);
console.log(newLength); // 5
console.log(numbers); // [1, 3, 4, 5, 6]You can use unshift() to put a new notification at the front of a local list.
11. includes() — Check whether a value exists
includes() returns true when it finds the value and false otherwise. For ordinary values, types matter. The number 5 and the string "5" are different values.
const numbers = [3, 4, 5, 6];
console.log(numbers.includes(5)); // true
console.log(numbers.includes(9)); // false
console.log(numbers.includes("5")); // falseFor objects, includes() compares references. To search for an object by a property, use find() or some() with a condition.
12. filter() — Keep all matching items
filter() creates a new array containing every item that passes the condition. When nothing matches, it returns an empty array.
const numbers = [3, 4, 5, 6];
const matches = numbers.filter((num) => num > 4);
console.log(matches); // [5, 6]
console.log(numbers.filter((num) => num > 10)); // []
console.log(numbers); // [3, 4, 5, 6]Use filter() to show only available products or completed tasks.
13. every() — Check whether all items pass
every() returns true if all the checked items pass your condition. It stops as soon as one fails. On an empty array it returns true because there is no item that fails the condition.
const numbers = [3, 4, 5, 6];
console.log(numbers.every((num) => num > 5)); // false
console.log(numbers.every((num) => num > 2)); // true
console.log([].every((num) => num > 5)); // trueIf a form needs at least one selected item and every selected item must be valid, check the length as well as every().
14. findIndex() — Get the position of the first match
findIndex() returns the index of the first item that passes the condition. When there is no match, it returns -1. A match at position zero is valid.
const numbers = [3, 4, 5, 6];
console.log(numbers.findIndex((num) => num > 4)); // 2
console.log(numbers.findIndex((num) => num === 3)); // 0
console.log(numbers.findIndex((num) => num > 10)); // -1Check index !== -1 before using the result. An if (index) check would reject zero and accept -1.
15. reduce() — Build one accumulated result
reduce() passes a running result through the array. Here acc is the total so far and num is the current number. The final 0 sets the starting total. The callback returns the total for the next step.
const numbers = [3, 4, 5, 6];
const total = numbers.reduce((acc, num) => acc + num, 0);
console.log(total); // 18
console.log([].reduce((acc, num) => acc + num, 0)); // 0With this initial value, the total goes from 0 to 3, then 7, then 12, and finally 18. reduce() can also build an object or another array. Calling it on an empty array without an initial value throws a TypeError.
Quick reference
Method | Returns | Changes the original array? |
|---|---|---|
| Removed item | Yes |
| New length | Yes |
| Same array, reversed | Yes |
| New array | No |
| First matching item or undefined | No |
| Item or undefined | No |
| Same array, filled | Yes |
| String | No |
| Removed item | Yes |
| New length | Yes |
| Boolean | No |
| New array | No |
| Boolean | No |
| Index or -1 | No |
| Accumulated result | No |
The last column describes the built-in method's own behavior. A callback you write can still change an array or an object. Also, copied arrays can share the same nested objects.
A practical example with a shopping cart
Imagine a customer buys two notebooks at ৳80 each and one pen at ৳20. We can filter for available products, calculate each line total, and add the totals together.
const cart = [
{ name: "Notebook", price: 80, quantity: 2, available: true },
{ name: "Pen", price: 20, quantity: 1, available: true },
{ name: "Pencil", price: 10, quantity: 3, available: false }
];
const total = cart
.filter((item) => item.available)
.map((item) => item.price * item.quantity)
.reduce((sum, lineTotal) => sum + lineTotal, 0);
console.log(total); // 180filter() keeps the notebook and pen. map() produces [160, 20]. reduce() adds those numbers and returns 180. This short chain is easy to follow because each step has one clear job.
Common mistakes to watch for
Assigning the result of push() back to the array
Because push() returns a number, assigning its result to a variable replaces that variable's value with the new length. Call push() on the array and keep its returned length in a separate variable if you need it.
Forgetting return inside a callback with braces
An arrow callback without braces returns its expression automatically. Once you add braces, write return yourself.
const numbers = [3, 4, 5, 6];
const missingReturn = numbers.map((num) => {
num + 6;
});
console.log(missingReturn); // [undefined, undefined, undefined, undefined]
const increased = numbers.map((num) => {
return num + 6;
});
console.log(increased); // [9, 10, 11, 12]Expecting filter() to copy nested objects
filter() creates a new outer array. The objects inside can still be shared with the original array. Changing a property on one of those objects is visible through both arrays. With map(), return a new object when you want to update an object without changing the original one.
Changing React state arrays directly
When an array is stored in React state, use a new array for an update. For example, setItems((previous) => [...previous, newItem]) adds an item using the previous state. To reverse the order, copy the array before calling reverse().
Frequently asked questions
What is the difference between map() and filter()?
Use map() to produce a value for each existing item. Use filter() to choose which items to keep. For the regular arrays in this guide, map() preserves the length, while filter() can return fewer items.
What is the difference between find() and filter()?
find() returns the first matching item or undefined. filter() returns an array of all matching items, which can be empty.
Can I use const with an array that changes?
Yes. const prevents reassignment of the variable. You can still change the contents of its array with methods such as push() and pop().
Do these examples cover arrays with empty slots?
The examples use arrays with a value at every position. Arrays with empty slots have additional rules. For example, map(), filter(), every(), and reduce() skip empty slots when there is no inherited indexed property at that position. find() and findIndex() visit the positions and typically receive undefined for the empty slots. An empty slot and an explicitly stored undefined value can behave differently.
Practice with a small list
Try an array of five product prices. Use filter() to keep prices above ৳100, map() to add ৳10 to each selected price, and reduce() to calculate the total. Then use find() to get the first price above ৳100 and compare its result with filter(). Log both the returned value and the original array after each call.
I hope you find it well, if you have any question about me, you can email me. Or you can give some feedback in one minute in the guestbook
Allah Hafez 👋
Comments
Join the discussion. Sign in with Google to post; your email is never shown.