JavaScript Array Methods
Table of Contents + β
In the previous lesson, we learned how to create arrays and read their values. Now letβs learn the built-in array methods that let us add items, remove items, and search through an array.
π§° What are Array Methods?
Array methods are functions that come built into every array. We call them with a dot after the array name, like numbers.push(5). They save us from writing the same logic by hand every time we want to change or inspect an array.
Here are the most common ones, with what each does and a quick example.
| Method | What it does | Example |
push | Adds an item to the end | fruits.push("kiwi") |
pop | Removes the last item | fruits.pop() |
unshift | Adds an item to the start | fruits.unshift("kiwi") |
shift | Removes the first item | fruits.shift() |
indexOf | Returns the position of an item, or -1 | fruits.indexOf("kiwi") |
includes | Returns true or false if an item exists | fruits.includes("kiwi") |
slice | Returns a copy of part of the array | fruits.slice(0, 2) |
splice | Adds or removes items at a position | fruits.splice(1, 1) |
join | Joins all items into one string | fruits.join(", ") |
β Adding and Removing Items
Four methods handle the ends of an array. We use push and pop to work with the end, and unshift and shift to work with the start.
const fruits = ["apple", "banana"];
fruits.push("cherry"); // add to the endconsole.log(fruits); // ["apple", "banana", "cherry"]
fruits.pop(); // remove from the endconsole.log(fruits); // ["apple", "banana"]
fruits.unshift("mango"); // add to the startconsole.log(fruits); // ["mango", "apple", "banana"]
fruits.shift(); // remove from the startconsole.log(fruits); // ["apple", "banana"]Letβs walk through how each method reshapes the same fruits array:
fruits.push("cherry")tacks"cherry"onto the end, giving us three items.fruits.pop()strips off that last item again, leaving the original two.fruits.unshift("mango")slides"mango"in at the front, so it becomes the first item.fruits.shift()removes that first item, returning us to["apple", "banana"].
The push and unshift methods return the new length of the array, while pop and shift return the item they removed.
const colors = ["red", "green"];
const removed = colors.pop();console.log(removed); // "green" β the item that was removedHere colors.pop() removes "green" and hands it back, so the removed variable now holds the item we just took off the end.
π Searching an Array
To find out whether an item is in an array, we use indexOf or includes. They answer slightly different questions.
The indexOf method tells us the position of an item, and returns -1 when the item is not found.
const animals = ["cat", "dog", "fish"];
console.log(animals.indexOf("dog")); // 1console.log(animals.indexOf("bird")); // -1 β not foundThese two lines show both outcomes:
animals.indexOf("dog")returns1because"dog"sits at index1(counting from0).animals.indexOf("bird")returns-1because"bird"is not in the array at all.
The includes method is simpler when we only want a yes or no answer. It returns a boolean, true or false.
const animals = ["cat", "dog", "fish"];
console.log(animals.includes("dog")); // trueconsole.log(animals.includes("bird")); // falseThe result is a plain yes-or-no answer:
animals.includes("dog")returnstruebecause"dog"is in the array.animals.includes("bird")returnsfalsebecause"bird"is missing.
Pick the right tool
Use includes when you only need to know whether an item exists. Use
indexOf when you also need to know where it is.
βοΈ slice vs splice
These two look alike but behave very differently. The slice method copies a section of the array into a brand new array and leaves the original untouched. The splice method changes the original array by removing or adding items.
const numbers = [10, 20, 30, 40];
// slice copies β original stays the sameconst part = numbers.slice(1, 3);console.log(part); // [20, 30]console.log(numbers); // [10, 20, 30, 40]
// splice changes the originalnumbers.splice(1, 1); // remove 1 item at index 1console.log(numbers); // [10, 30, 40]Letβs compare what each call does to numbers:
numbers.slice(1, 3)copies the items from index1up to (but not including) index3, returning[20, 30]as a new array.- Logging
numbersright after provessliceleft the original[10, 20, 30, 40]untouched. numbers.splice(1, 1)removes1item starting at index1, deleting20directly from the original.- The final log shows
numbersis now[10, 30, 40], becausespliceedited it in place.
An easy one to mix up
Remember: slice is safe and returns a copy, while splice edits the array
in place. The extra βpβ in splice is a reminder that it βputs and pullsβ
items out of the original.
π Turning an Array into a String
The join method takes every item and glues them together into a single string. We choose the separator that goes between items.
const words = ["learn", "to", "code"];
console.log(words.join(" ")); // "learn to code"console.log(words.join("-")); // "learn-to-code"The separator we pass in decides what sits between the items:
words.join(" ")puts a space between each item, producing"learn to code".words.join("-")uses a hyphen instead, producing"learn-to-code".
This is handy for building a sentence or a path from a list of pieces.
π Methods That Change vs Methods That Return
This is the most important idea to hold onto. Some methods change the original array, and others leave it alone and hand back a new value. Mixing these up is a common source of bugs.
| Method | Changes the original? | What it gives back |
push / unshift | Yes (mutates) | The new length |
pop / shift | Yes (mutates) | The removed item |
splice | Yes (mutates) | An array of removed items |
slice | No | A new array |
indexOf | No | A number (position or -1) |
includes | No | A boolean |
join | No | A string |
π A Practical Example: A To-Do List
Letβs put these methods together to manage a simple to-do list. We start with a few tasks, add and remove some, and check what is on the list.
const todos = ["wash dishes", "buy groceries"];
// Add a new task to the endtodos.push("walk the dog");console.log(todos); // ["wash dishes", "buy groceries", "walk the dog"]
// Add an urgent task to the fronttodos.unshift("call the dentist");console.log(todos);// ["call the dentist", "wash dishes", "buy groceries", "walk the dog"]
// Finish the first task and remove itconst done = todos.shift();console.log(done); // "call the dentist"
// Check if a task is on the listconsole.log(todos.includes("buy groceries")); // true
// Remove a specific task by finding its positionconst index = todos.indexOf("buy groceries");todos.splice(index, 1);console.log(todos); // ["wash dishes", "walk the dog"]
// Show the list as one readable stringconsole.log(todos.join(", ")); // "wash dishes, walk the dog"Letβs follow the to-do list step by step:
todos.push("walk the dog")adds a new task to the end of the list.todos.unshift("call the dentist")puts an urgent task at the very front.todos.shift()removes that first task and stores it indone, sinceshiftreturns the removed item.todos.includes("buy groceries")returnstrue, confirming the task is still on the list.todos.indexOf("buy groceries")finds the taskβs position, thentodos.splice(index, 1)removes one item at that position.todos.join(", ")glues the remaining tasks into one readable string.
With just these methods, we can add, remove, search, and display the items in any list.
More powerful methods are coming
These methods cover adding, removing, and searching. Next we will meet
map, filter, find, and reduce, the iteration methods that let us
transform and summarize an entire array at once.
β οΈ Common Mistakes to Avoid
| Mistake | Problem | Solution |
Confusing push and unshift | The item ends up at the wrong end of the array | Use push for the end, unshift for the start |
Confusing slice and splice | splice changes the original when you only wanted a copy | Use slice to copy, splice to edit in place |
Forgetting includes returns a boolean | Treating its result like a position breaks your logic | Use includes for true/false, indexOf for the position |
Checking indexOf(...) > 0 to test existence | The first item is at index 0, so it gets missed | Check indexOf(...) !== -1, or just use includes |
Here is the difference between the right and wrong existence check:
const names = ["Alex", "Sam"];
// β Wrong β misses the first item at index 0if (names.indexOf("Alex") > 0) { console.log("found");}
// β
Correctif (names.includes("Alex")) { console.log("found");}Letβs see why one check fails and the other works:
"Alex"sits at index0, sonames.indexOf("Alex")returns0, and0 > 0isfalseβ the wrong check skips the item.names.includes("Alex")returnstrueno matter the position, so the correct check always finds the item.
π§ Try It Yourself!
- Create an array of three favorite foods.
- Use
pushto add a food to the end, thenunshiftto add one to the start. - Use
popto remove the last food and store the removed value in a variable. - Use
includesto check whether one of your foods is still in the array. - Use
join(", ")to print the whole array as a single sentence.
π§© What Youβve Learned
- β
push,pop,unshift, andshiftadd and remove items at the ends - β
indexOfreturns a position (or-1), andincludesreturnstrueorfalse - β
slicecopies part of an array, whilespliceedits the array in place - β
jointurns an array into a single string - β
push,pop,shift,unshift, andsplicemutate the array;slice,join,includes, andindexOfreturn a new value
π Whatβs Next?
Now that we can add, remove, and search, letβs learn the most useful iteration method for transforming an array. Letβs continue to The map() Method.