Not only numbers can be written in square brackets. Any expression can be formatted this way. In the end, this expression will be converted to a number.
Let’s practice this way of accessing array elements and alternate them with the same variable. To do this, you need to get a variable to store the current index of the array element. Let’s call it index and write the initial zero value in it.
If you now log the expression usersByDay[index] in the console, we’ll see the first value of the array. After all, now the variable holds zero, and the expression usersByDay[index] is equivalent to usersByDay.
If you change the value of the variable index from zero to one and access usersByDay[index] again, we’ll then get an element with the index 1, that is, the second element.
Look, the expression in brackets in both cases is the same: usersByDay[index]. But it returns different values for different conditions.
If we continue to increase index and read elements of the array usersByDay, then sooner or later we will go through all the elements.
var usersByDay = [812, 1360, 657, 1247];
The code has changed, click “Run” or turn autorun on.
Let’s get the elements of the array by manually changing the index variable.
After the array, declare the variable index with a zero value.
On the next line, log usersByDay[index] in the console.
On the next line, set the variable index value 3.
On the next line, once again log usersByDay[index] in the console.
Have you forgotten your password or lost access to your profile? Enter your email connected to your profile and we will send you a link to restore access.
Forgot to connect your email to the profile? Email us and we’ll help.