1-9 Arrays - Learn Web Development - MDN
1-9 Arrays - Learn Web Development - MDN
Arrays
In the final article of this module, we'll look at arrays — a neat way of storing a list of data
items under a single variable name. Here we look at why this is useful, then explore how to
create an array, retrieve, add, and remove items stored in an array, and more besides.
What is an array?
Arrays are generally described as "list-like objects"; they are basically single objects that
contain multiple values stored in a list. Array objects can be stored in variables and dealt
with in much the same way as any other type of value, the difference being that we can
access each value inside the list individually, and do super useful and efficient things with
the list, like loop through it and do the same thing to every value. Maybe we've got a
series of product items and their prices stored in an array, and we want to loop through
them all and print them out on an invoice, while totaling all the prices together and printing
out the total price at the bottom.
If we didn't have arrays, we'd have to store every item in a separate variable, then call the
code that does the printing and adding separately for each item. This would be much
longer to write out, less efficient, and more error-prone. If we had 10 items to add to the
invoice it would already be annoying, but what about 100 items, or 1000? We'll return to
this example later on in the article.
As in previous articles, let's learn about the real basics of arrays by entering some
examples into browser developer console.
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays 1/13
27/06/2023, 09:48 Arrays - Learn web development | MDN
Creating arrays
Arrays consist of square brackets and items that are separated by commas.
1. Suppose we want to store a shopping list in an array. Paste the following code into the
console:
JS
const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
console.log(shopping);
2. In the above example, each item is a string, but in an array we can store various data
types — strings, numbers, objects, and even other arrays. We can also mix data types
in a single array — we do not have to limit ourselves to storing only numbers in one
array, and in another only strings. For example:
JS
const sequence = [1, 1, 2, 3, 5, 8, 13];
const random = ["tree", 795, [0, 1, 2]];
2. You can also modify an item in an array by giving a single array item a new value. Try
this:
JS
const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
shopping[0] = "tahini";
console.log(shopping);
// shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ]
3. Note that an array inside an array is called a multidimensional array. You can access
an item inside an array that is itself inside another array by chaining two sets of
square brackets together. For example, to access one of the items inside the array
that is the third item inside the random array (see previous section), we could do
something like this:
JS
const random = ["tree", 795, [0, 1, 2]];
random[2][2];
4. Try making some more modifications to your array examples before moving on. Play
around a bit, and see what works and what doesn't.
Adding items
To add one or more items to the end of an array we can use push() . Note that you need to
include one or more items that you want to add to the end of your array.
JS
const cities = ["Manchester", "Liverpool"];
cities.push("Cardiff");
console.log(cities); // [ "Manchester", "Liverpool", "Cardiff" ]
cities.push("Bradford", "Brighton");
console.log(cities); // [ "Manchester", "Liverpool", "Cardiff", "Bradford", "Brighton" ]
The new length of the array is returned when the method call completes. If you wanted to
store the new array length in a variable, you could do something like this:
JS
const cities = ["Manchester", "Liverpool"];
const newLength = cities.push("Bristol");
console.log(cities); // [ "Manchester", "Liverpool", "Bristol" ]
console.log(newLength); // 3
Removing items
To remove the last item from the array, use pop() .
JS
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays 4/13
27/06/2023, 09:48 Arrays - Learn web development | MDN
The pop() method returns the item that was removed. To save that item in a new variable,
you could do this:
JS
const cities = ["Manchester", "Liverpool"];
const removedCity = cities.pop();
console.log(removedCity); // "Liverpool"
If you know the index of an item, you can remove it from the array using splice() :
JS
const cities = ["Manchester", "Liverpool", "Edinburgh", "Carlisle"];
const index = cities.indexOf("Liverpool");
if (index !== -1) {
cities.splice(index, 1);
}
console.log(cities); // [ "Manchester", "Edinburgh", "Carlisle" ]
In this call to splice() , the first argument says where to start removing items, and the
second argument says how many items should be removed. So you can remove more than
one item:
JS
const cities = ["Manchester", "Liverpool", "Edinburgh", "Carlisle"];
const index = cities.indexOf("Liverpool");
if (index !== -1) {
cities.splice(index, 2);
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays 5/13
27/06/2023, 09:48 Arrays - Learn web development | MDN
}
console.log(cities); // [ "Manchester", "Carlisle" ]
JS
const birds = ["Parrot", "Falcon", "Owl"];
Sometimes you will want to do the same thing to each item in an array, leaving you with an
array containing the changed items. You can do this using map() . The code below takes an
array of numbers and doubles each number:
JS
function double(number) {
return number * 2;
}
const numbers = [5, 2, 7, 6];
const doubled = numbers.map(double);
console.log(doubled); // [ 10, 4, 14, 12 ]
We give a function to the map() , and map() calls the function once for each item in the
array, passing in the item. It then adds the return value from each function call to a new
array, and finally returns the new array.
Sometimes you'll want to create a new array containing only the items in the original array
that match some test. You can do that using filter() . The code below takes an array of
strings and returns an array containing just the strings that are greater than 8 characters
long:
JS
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays 6/13
27/06/2023, 09:48 Arrays - Learn web development | MDN
function isLong(city) {
return city.length > 8;
}
const cities = ["London", "Liverpool", "Totnes", "Edinburgh"];
const longer = cities.filter(isLong);
console.log(longer); // [ "Liverpool", "Edinburgh" ]
Like map() , we give a function to the filter() method, and filter() calls this function for
every item in the array, passing in the item. If the function returns true , then the item is
added to a new array. Finally it returns the new array.
Note: Okay, this is technically a string method, not an array method, but we've
put it in with arrays as it goes well here.
1. Let's play with this, to see how it works. First, create a string in your console:
JS
const data = "Manchester,London,Liverpool,Birmingham,Leeds,Carlisle";
3. Finally, try finding the length of your new array, and retrieving some items from it:
JS
cities.length;
cities[0]; // the first item in the array
cities[1]; // the second item in the array
cities[cities.length - 1]; // the last item in the array
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays 7/13
27/06/2023, 09:48 Arrays - Learn web development | MDN
4. You can also go the opposite way using the join() method. Try the following:
JS
const commaSeparated = cities.join(",");
commaSeparated;
limiting. With join() you can specify different separators, whereas toString() always
uses a comma. (Try running Step 4 with a different character than a comma.)
JS
const dogNames = ["Rocket", "Flash", "Bella", "Slugger"];
dogNames.toString(); // Rocket,Flash,Bella,Slugger
code the correct total is printed onto the invoice. You might need an assignment
operator to do this.
6. We want you to change the line just below // number 5 so that the itemText variable is
made equal to "current item name — $current item price", for example "Shoes —
$23.99" in each case, so the correct information for each item is printed on the
invoice. This is just simple string concatenation, which should be familiar to you.
7. Finally, below the // number 6 comment, you'll need to add a } to mark the end of the
for...of() loop.
Play
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays 9/13
27/06/2023, 09:48 Arrays - Learn web development | MDN
Live output
Total: $0.00
Editable code
Press Esc to move focus away from the code area (Tab inserts a tab character).
// number 2
// number 3
// number 4
// number 5
let itemText = 0;
// number 6
In this example we're going to show a much simpler use — here we're giving you a fake
search site, with a search box. The idea is that when terms are entered in the search box,
the top 5 previous search terms are displayed in the list. When the number of terms goes
over 5, the last term starts being deleted each time a new term is added to the top, so the
5 previous terms are always displayed.
Note: In a real search app, you'd probably be able to click the previous search
terms to return to previous searches, and it would display actual search results!
We are just keeping it simple for now.
To complete the app, we need you to:
1. Add a line below the // number 1 comment that adds the current value entered into
the search input to the start of the array. This can be retrieved using
searchInput.value .
2. Add a line below the // number 2 comment that removes the value currently at the
end of the array.
Play
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays 11/13
27/06/2023, 09:48 Arrays - Learn web development | MDN
Conclusion
After reading through this article, we are sure you will agree that arrays seem pretty darn
useful; you'll see them crop up everywhere in JavaScript, often in association with loops in
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays 12/13
27/06/2023, 09:48 Arrays - Learn web development | MDN
order to do the same thing to every item in an array. We'll be teaching you all the useful
basics there are to know about loops in the next module, but for now you should give
yourself a clap and take a well-deserved break; you've worked through all the articles in
this module!
The only thing left to do is work through this module's assessment, which will test your
understanding of the articles that came before it.
See also
Indexed collections — an advanced level guide to arrays and their cousins, typed
arrays.
Array — the Array object reference page — for a detailed reference guide to the
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays 13/13