You need to know how to do three things with arrays:
- Find the position of an item
- Add an item to the array
- Remove an item from the array
As you go through this lesson, you’ll see various ways to do these tasks in JavaScript. They are all correct. Over time, you’ll learn to choose the methods you prefer. For now, focus on understanding how each method works.
Finding the Position of an item
To locate a primitive value in an array, use indexOf
. It returns the index of the item if found, otherwise, it returns -1
.
For objects, arrays, or functions use findIndex
Adding Items to an Array
You can add items to the start, end, or middle of an array. Let’s start with the beginning and end.
Start: Use unshift
to add items to the start
End: Use push
to add items to the end
Removing Items from an Array
You can remove items from the start, end, or middle of an array. Let’s start with the beginning and end.
Start: Use shift
to remove items from the start
End: Use pop
to remove items from the end
The Almighty splice
Method
splice
lets you add or remove items from any position in an array. The syntax is:
index
: Where to start modifying the array.deleteCount
: Number of items to delete.itemsToAdd
: Items to add.
Add Items:
Remove Items:
Making a Copy of an Array
Use slice
to create a copy of an array. Modifying the copy won’t change the original array.
By the end of this guide, you’ll be well-equipped to handle arrays with confidence. Happy coding!