List Methods
Introduction
Just like string methods we learned last lesson, there are also a ton of methods we can use to manipulate and change lists! Lists are very important in Javascript since most of the data that you use will be used in lists, and knowing how to play around with that data is very important. In this lesson, we will learn skills like adding or removing items to list, sorting them, or replacing certain list items. Let’s go ahead and get started!
Overview
By the end of this lesson, you should be able to:
- Understand how to take indexes of lists and use them
- Understand how to add and remove items from a list using
.push()
and.pop()
- Learn how to add in and remove items from the beginning of a list
- Learn how to use the methods
.sort()
,.reverse()
, and.splice()
Lists and Indexes
In the last lesson, we learned about how we can use indexes to find specific characters of our string and how we can use some string methods to get specific parts. Well we can do the same thing with lists in Javascript. Let’s take a look at how it is done with lists:
As you can see, using indexes in our lists works exactly like it does with strings. Each item in the list has an index starting from 0 and going to 1. Using indexes, we are able to call certain items from our list like this:
Length of a List
We are able to add as many list items as we want to a list in Javascript and call any list items we want. Just like with strings, we can also take the length of lists like this:
let foods = ["Pasta", "Pizza", "Cake"]
let numbers = [1,2,3,4,5,6,7,8]
let randomTypes = [true, "17", "281", "string2"]
console.log(foods.length) // Logs "3"
console.log(numbers.length) // Logs "9"
console.log(randomTypes.length) // Logs "4"
So here’s a question for you: How can you get the last element of a list using your knowledge of .length and list indexes? Think about and when you’re ready, open the answer toggle to see if you’re correct
We can get the last element of a list by taking the length and then subtracting 1
from that. The reason why we remove 1 is because string indexes start from 0
while the .length()
method starts from 1. Here’s an example:
Using .push() and .pop
.push()
Declaring lists are easy, but if we want to add some information to our lists? The .push()
method makes this easy, take a look on how it works:
let fruits = ["apple", "banana", "orange"];
fruits.push("pear");
console.log(fruits); // Logs ["apple", "banana", "orange", "pear"]
This should be pretty straightforward. We start by choosing our lists and then inside of the .push()
method, we put in what we want to add. We can append strings, integers, booleans and even other lists to our existing lists.
So why would we want to use this? Let’s say we have a list of all the users that are signed up on our website. What if a new user signs up, how will their information we added to the list of usernames and passwords? We could use the .push()
method to add their username and password into our already existing list so the next time they login, we can check! And that is just one example, down the road as you start using lists more, you will find yourself using the .push()
method.
.pop()
So we know how to add something to a list, but what if we wanted to remove the last element from a list? There is where the .pop()
method comes in. Take a look at how it works:
let myArray = [1, 2, 3, 4, 5];
let poppedValue = myArray.pop();
console.log(myArray); // Output: [1, 2, 3, 4]
console.log(poppedValue); // Output: 5
The .pop()
method is a very simple one to understand as well. We just take the list we want to remove the last element from and put .pop()
after it.
Something to note is that .pop()
ONLY removes the last element. Later on in this lesson, we will learn about the .splice()
method which helps us remove elements from a certain index in our lists. But for now, just understand that the .pop()
method removes the last element from the list. The last thing regarded .pop()
we will cover is how to assign the popped item from our list to a variable. Here is how we do it:
let foods = ["Pasta", "Pizza", "Cake"]
let popped_item = foods.pop()
console.log(foods) // Logs ["Pasta", "Pizza"]
console.log(popped_item) // Logs: "Cake"
In this example, we are still removing the last element, but now we are setting that popped element to a variable. Here, we are setting the last removed element to the variable popped_item
. Now when we log popped_item
to the console, we will see that we get Cake
since that was the last element that we removed which was stored in popped_item
.
Using .shift() and .unshift()
The .shift()
and .unshift()
methods are really similar to .push()
and .pop()
.The only main difference is that push
and pop
methods either removes the last element of a list or adds an item to the beginning of the list while the shift
and unshift
methods change the g from the beginning rather than the end. Let’s start by looking at the .shift()
method first.
.shift()
The .shift()
method is really similar to the .pop()
method. Instead of removing the last element like .pop()
does, .shift()
will remove the first element. Take a look at how it works:
As you can see, calling the .shift()
method removes the very first element or list item from the list that we choose. This could be useful in some instances. Let’s say a user changes their name on a profile, we can remove the first element (preferably their name) and replace it with their new name and store that data. Now let’s see how .unshift()
works.
.unshift()
The .unshift()
method is like the .push()
method in the sense that we are adding things to our list, but instead of adding to the end of the list, .unshift()
adds our list items to the beginning of the list. Here is it working in action:
As you can see, using .unshift()
will add in whatever element that we want to our list of choosing, but it will add the element in the beginning of our list rather than the end.
These methods are more niche and you won’t find yourself using them that often, but they are good to know in the case that you do need to use them. In the next few sections, we’ll learn some more important methods like .sort()
, .reverse()
and .splice()
. Let’s get started!
Sort, Reverse, and Splice Methods
By now, we know how to manipulate lists by adding items, removing items from the beginning and end and also taking the length of a list. Now we will learn skills like sorting our lists, reversing them, and deleting specific indexes/elements from our list.
.sort()
The .sort()
has many different uses. For starters, .sort()
allows us to sort a list alphabetically like this:
let foods = ["banana", "carrot", "apple"]
foods.sort()
console.log(foods)
// Logs ["apple", "banana", "carrot"]
let countries = ["Ukraine", "Canada", "Brazil", "Turkey"]
countries.sort()
console.log(countries)
// Logs ["Brazil", "Canada", "Turkey", "Ukraine"]
The .sort()
method is very simple. All it does is sort the contents of the list alphabetically. In the first example, since apple
starts with an a
while all the other list items start with letters after it, apple
is the very first element in the list. What if our list has integers instead of strings? Well .sort()
also sorts integers in order as well. Here’s how it’s done:
let numbers = [7,3,9,1,6]
numbers.sort()
console.log(numbers)
// Logs [1,3,6,7,9]
.reverse()
The .reverse()
method works exactly like how you would expect it to work. It will reverse the contents of a list so that the last item is now the first and the first item is now the last. Take a look at these two examples below:
let foods = ["Pasta", "Pizza", "Cake"]
foods.reverse()
console.log(foods)
// Logs ["Cake", "Pizza", "Pasta"]
let numbers = [1,2,3,4,5,6,7,8]
numbers.reverse()
console.log(numbers)
// Logs [8, 7, 6, 5, 4, 3, 2, 1]
let randomTypes = [true, "17", "281", "string2"]
randomTypes.reverse()
console.log(randomTypes)
// Logs ["string2", "281", "17", true]
Once again, this method is more niche, but there may be instances in which you might want to use it. When you’re playing around with a lot of user data, you will find these methods useful to you down the road!
.splice()
In the last few sections, we learned how to remove elements that are at the end of a list and elements that are at the beginning of a list. .splice()
is also a method that removes elements, but with splice, we can choose exactly which elements to remove and we can even add in some elements. Before seeing an example, take a look at the parameters you give the .splice()
method
Ok, let’s take a look at what is happening with these parameters. Our very first twoparameters will be our starting and ending index. These are the items that we want to remove or splice from our list. Note that the endingindex
won’t count the last number. If you want to splice 5 items, our parameters might be .splice(0,6)
since the6th listitem is not counted.
Now let’s talk about the parameters after those beginning two. The “items” that you see after are the items that will replace the ones you removed. In the example above, we are replacing all the spliced items with item1, item2, item..
Let’s take a look at how this will play out in real code.
let numbers = [1,2,3,4,5,6,7,8,9]
numbers.splice(0,4,3) // Splicing first four numbers with number 3
console.log(numbers)
// Logs [3, 5, 6, 7, 8, 9]
let colors = ["red", "blue", "green", "yellow"]
colors.splice(0,2,"purple") // Splicing first 2 items with "purple"
console.log(colors)
// Logs ["purple", "green", "yellow"]
Ok so what is happening in the first example? In the first list, we have all the numbers from 1 – 9. We are splicing or removing the first 4 list-items from the list and replacing them with the number 3.You can see the output right under it.
In the second example, we have a list of colors. We are removing the first 2 elements of the list and then replacing them with the color purple
. The .splice()
method is one of the more powerful methods from the different ones that we discussed in this lesson. As you start to code more, you will find this method to be useful in some instances.
By now, you should have a simple understanding of a lot of the basic list methods. Let’s do some quick practice before moving onto for
and while
loops in the next lesson!
Closing Note:
Just like with String Methods, JavaScript offers us a large amount of nice methods to use. This lesson covered the main important ones, but theres a lot we haven’t talked about yet. Below are some additional resources going over new methods + the ones covered in this lesson.
Additional Resources:
- This w3schools lesson goes over what we covered today along with some more list methods
- Here is another lesson on the Mozilla Web Docs. This one is more advanced and covers a lot more topics, so it’s a great way to learn
As always, feel free to join our discord server if you need any help. We have a great community and people willing to help!
Practice
- Start by defining an empty list called
nums
like this:let nums = []
- The first thing we’ll do is add something to our list. Use
.push()
to add the numbers1, 2, 3, 4, 5
to our list - Now using
.pop()
, remove the last two numbers4, 5
- Using
.shift()
, remove the very first element(1)
from our listnums
. - Now use
.unshift()
to add the numbers0, 7, and 9
, 7, .Make sure to add them in that order. - Using
.splice()
, remove the list items between the second and fifth indexes (not counting the fifth index) - Now using
.sort()
, sort the elements starting from lowest to highest. - Finally, use
.reverse()
to make our list sort from the highest to lowest.
- The first thing we’ll do is add something to our list. Use
And that’s all! Hopefully you understand and are able to comfortably use some of these important list methods. Throughout the next few lessons, we will be incorporating these methods into our exercises and projects, so feel free to always come back for a refresher. In the next lesson, we will continue to learn about loops.
Find an issue/typo/error with our content? Please report it here