Summary of “Arrays”. Part 1

An array is a data type representing an ordered list of elements, each identified by an index.

In the array you can store any data: strings, Boolean values, numbers and even other arrays.

Numbering of array elements starts from zero, therefore the sequence number (index) of the first element equals zero.

You can use a variable as an index.

Use the length property to read the array’s length (the number of elements for the arrays shown here). You can use the length minus one as the index to get the last element of the array.

var numbers = [1, 2, 3, 4, 5];
var index = 3;

// Will log 1 in the console
console.log(numbers[0]);

// Will log 4 in the console
console.log(numbers[index]);

// Will log 5 in the console
console.log(numbers.length);

// Will log 5 in the console
console.log(numbers[numbers.length - 1]);

You can loop through arrays. For example, the loop below logs array elements in the console one by one and stops working when i becomes equal to the length of the array.

var numbers = [1, 2, 3, 4, 5];

for (var i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

// Will log 1
// Will log 2
// Will log 3
// Will log 4
// Will log 5

Writing to an array uses square brackets, just as reading does, followed by an assignment.

var numbers = [];
var index = 1;

numbers[0] = 1;
numbers[index] = 2;

// Will log [1,2] in the console
console.log(numbers);

Continue