• 15 heures
  • Facile

Ce cours est visible gratuitement en ligne.

course.header.alt.is_video

course.header.alt.is_certifying

J'ai tout compris !

Mis à jour le 19/01/2024

Manage complexity with the right collection

Imagine you are the communication manager of a fashionable theater. One of your main responsibilities is to manage the front row, which means making sure that the artists' relatives and friends, as well as other VIPs, get the best view of the show.

If all you had to do was handle two invitations for the main artist, you could imagine using just two variables holding the guest's name. The code could look like this:

let firstFrontRowGuest;
let secondFrontRowGuest;

Then, when the performer gives you the information, you would just assign a name to each variable. For instance, you would have:

firstFrontRowGuest = 'Sarah Kate';
secondFrontRowGuest = 'Audrey Simon';

But what if the front row has 30 seats? Wouldn't it be easier if you could use just one variable that could serve as a collection of all that information?

Good news! There are objects for that called collections! 😎

And the most common type of collection in JavaScript the array.

Use an array to store an ordered list of elements

To create an empty array and store it in a variable, you use a pair of square brackets:

let guests = [];

You can also create a populated array by putting the desired elements inside those square brackets:

let guests = ['Sarah Kate', 'Audrey Simon', 'Will Alexander'];

You can then access elements of that array by their index:

let firstGuest = guests[0]; // 'Sarah Kate'
let thirdGuest = guests[2]; // 'Will Alexander'
let undefinedGuest = guests[12] // undefined

Practice creating an array!

Head to CodePen Exercise P1CH5a and follow the instructions below to create an array to store episodes of your TV show.

In a previous exercise, you created three instances of the Episode class as separate variables. In this exercise, you are going to group those variables together in a single array.

  1. Create an array stored in a variable called episodes, and populate it with the three variables firstEpisode, secondEpisode and thirdEpisode. Watch the page populate itself automatically!

  2. Try changing the order in which you add the episodes, and watch what happens as it refreshes.

Solution:

Once you've given it a go, watch me code a solution and see how your approach compares. And here is a new CodePen with a solution to the exercice.

A very important side note - value vs. reference

In JavaScript, primitive types like numbers, booleans, and strings are passed by value. This means that when you do something like this:

let numberOfGuests = 20;

let totalNumberOfGuests = numberOfGuests; // 20

It is the value 20, which is copied into the new variable, and no link is maintained between the two variables.

This is not the case with objects and arrays, which are passed by reference. If you are not aware of this, it can lead to some unexpected behaviors. For example:

let artistProfile = {
    name: 'Tau Perkington',
    age: 27,
    available: true
};

let allProfiles = [artistProfile]; // new Array containing the above object

artistProfile.available = false; // changing the object

console.log(allProfiles) // will show { name: 'Tau Perkington', age: 27, available: false }

Even though we created the array and passed it the object before modifying the object, you still see the modification in the array. This is because when using arrays and objects, you are passing references to the objects, as opposed to the value of the data within them. The variables  artistProfile  and  allProfiles  shown above contain references to the object and array in memory.

This can seem a bit tricky to understand, but with practice, you'll get the hang of it!

Working with arrays

Arrays in JavaScript are very powerful and have lots of attributes and methods which are extremely useful. Here is a brief introduction to a handful of them.

Counting elements

The length property of an array tells you how many elements there are in it:

let guests = ['Will Alexander', 'Sarah Kate', 'Audrey Simon'];
let howManyGuests = guests.length; // 3

Use dot notation to access the length property of your array. This may not be very useful in this example (seeing as we know how many guests we put in the array!), but there are many situations in which you will not know how many elements an array has in advance.

Adding and removing elements

To add an element to the end of an array, use its  push method:

guests.push('Tau Perkington'); // adds 'Tau Perkington' to the end of our guests array

You use dot notation to access the array's  push method and put the element you wish to add in parentheses.

If you want to add your element at the beginning of the array instead of the end, use the  unshift  method:

guests.unshift('Tau Perkington'); // 'Tau Perkington' is added at the beginning of the guests array

To remove the last element of an array, call itspop method, without passing any arguments:

guests.pop(); // removes the last element from the array

Practice working with arrays!

Head to CodePen Exercise P1CH5b and follow the instructions below to practice working with our array.

In this exercise, an empty episodes array has already been created.

  1. Using the episodes array's push method, add each episode one by one. Add the third episode twice.

  2. Using the pop method, remove the extraneous episode from the array.

  3. Create a variable called numberOfEpisodes which stores the length of the episodes array.

  4. Play around with adding and removing episodes, and see if everything still works properly!

Solution:

Once you've given it a go, watch me code a solution and see how your approach compares. And here is a new CodePen with a solution to the exercice.

Now that you've started to get a grip on arrays let's take a look at the other kinds of JavaScript collection: sets and maps.

In JavaScript, a set is an unordered list.  This means that you cannot reliably retrieve specific list elements, as they do not have a fixed index. Instead, you can add and remove elements (duplicates are not allowed), and check whether a set contains a certain element or not.  Sets can come in handy for things like storing which users are online at a given time so you can check if they are or not.

On the other hand, a map is an ordered list of key/value pairs. While this sounds like an object, there are some important differences. For example, keys can be any value (not just strings) in maps; you can easily find its  size, and its key/value pairs can be filtered or modified in certain circumstances.

Let's recap!

In this chapter:

  • You learned about collections.

  • You explored the most common collection in JavaScript: the array.

  • You learned how to create arrays, how to populate them, and some basic tools for manipulating them.

  • Finally, you learned about the concepts of sets and maps.

Exemple de certificat de réussite
Exemple de certificat de réussite