Lesson 6 - Arrays in JavaScript
In the previous exercise, Solved tasks for JavaScript lesson 5, we've practiced our knowledge from previous lessons.
In the previous lesson, Solved tasks for JavaScript lesson 5, we learned how to use loops. In today's JavaScript tutorial, we're going to introduce the array data structure.
Imagine that you want to store some information about multiple items, e.g.
you want to keep 10 numbers in memory, the last 30 mouse cursor positions, or
names of 50 users. Perhaps you realize that there must be an easier way than to
start typing variables like user1
, user2
... up until user50
. Despite the fact that there may be 1000
of them. How would we search for something in there? Definitely not like that!
If we need to store a larger amount of variables of the same
type, we can solve this problem using an array. We can imagine it as a
row of boxes, each of them containing one item. The boxes are numbered by
indexes, the first one has index 0
. We can also assign names to the
array items so we can index them using strings. In some programming languages,
we have to specify the array size and the type of its items before we can create
it. In JavaScript, we don't have to specify any of it and we can store anything
we want into an array. Arrays are related to loops because we usually use loops
to manipulate array items.
Creating an array
We create an array using the Array
object:
let a = new Array(); a[0] = 1;
We use brackets to access array items. In the example above, we stored the
number 1
at the first index (index 0
). We can also
create arrays using brackets. The following code works exactly the same as the
one above, but since it's shorter, we'll prefer this array syntax:
let a = []; a[0] = 1;
Filling an array using loops
Let's fill an array with the numbers from 1
to 11
using the for
loop:
let a = []; for (let i = 0; i < 10; i++) { a[i] = i + 1; }
In order to print the array, we'll append the following code to the current one:
for (let i = 0; i < a.length; i++) { document.write(a[i] + " "); }
Notice that the array has the length
property where it's length
is stored (the number of its items).
The result:
Foreach
We can use a simplified version of the loop, foreach, to read all the items of an array. This kind of loop is often used for working with collections. It iterates through the array items and determines the array's length automatically:
let items = []; // There would be a code filling the array with some values // ... for (item of items) { document.write(item); }
In the past, there was also the for...in
loop in
JavaScript. But it's been deprecated because it carried the
index in its variable instead of the item,
which was confusing.
Filling an array with items directly
Of course, we can fill an array manually too. We'd choose this approach e.g. to store the days of the week. We'll program this example now.
Let's start with printing the day of the week. We'll use the
getDay()
method to do so. We call the method on the
Date
object and it returns the day of the week, starting with
Sunday.
let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; let d = new Date(); let day = d.getDay(); // returns a number between 0 - 6 document.write("Today is " + days[day]);
The script creates a string array of the names of the week. Then it gets the number of the current day. Finally, it prints the appropriate array item according to the current day number.
We can feel free to add or remove array items:
let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]; days.push("Saturday"); // adds a new item at the end of the array days.unshift("Sunday"); // adds a new item at the beginning of the array days.splice(2, 3); // removes the 3rd a 4th item (indexes are zero-based)
Sorting array items
We can easily sort array items using the sort()
method. If we
don't provide additional parameters, the items will be ordered alphabetically
(ascending):
let words = ['Delta', 'Bravo', 'Echo', 'Charlie', 'Alpha']; words.sort(); // Changes the words to ["Alpha", "Bravo", "Charlie", "Delta", "Echo"]
Unfortunatelly, if there're numbers in the array, they'd be ordered
alphabetically as strings too, meaning e.g. the number 25
would be
before 3
. We can modify the behavior of the sorting function by
passing an anonymous function (we'll explain those in details in the next
lesson). Sorting the array in these manners would look as following:
let numbers = [5, 3, 1, 30, 25, 80]; numbers.sort(function(a, b) { return a - b }); // Changes numbers to [1, 3, 5, 25, 30, 80]
We can reverse the order of the array items using the reverse()
method:
days.reverse(); // reverses the order in the way the items will be backwards
And this is the end of working with date and time for us. In the next lesson, Solved tasks for JavaScript lesson 6, we'll introduce functions which are fundamental for JavaScript and we wouldn't be able to do much without them.
In the following exercise, Solved tasks for JavaScript lesson 6, we're gonna practice our knowledge from previous lessons.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 5x (1.67 kB)
Application includes source codes in language JavaScript