Arrays are lists that store data in.
We use the new
keyword to construct an array.
const numbers = new Array(1, 2, 3);
console.log(numbers); // [1, 2, 3]
We can create an array by wrapping items in square brackets []. An array is 0 based.
const names = ["John", "Ana", "Peter"];
console.log(names[1]); // Ana
Variables that contain arrays can be declared with let or const.
Although variables declared with the const
keyword cannot be reassigned, elements in an array declared with const remain mutable.
Meaning that we can change the contents of a const array but cannot reassign a new array or a different value.
const students = ["John", "Ana", "Peter", "Noah"];
students[3] = "Mira";
console.log(students); // Output: ['John', 'Ana', 'Mira', 'Noah']
To copy arrays, we use the spread operator.
const itemsCopy = [...items];
Example:
const arr1 = [1, 2, 3, 4, 5];
let arr2;
(function () {
arr2 = [...arr1];
arr1[0] = 10;
})();
console.log(arr2); // [ 1, 2, 3, 4, 5 ]
Each element in an array has a numbered position known as its index, starting at 0.
We can access one item in an array using its index with the syntax myArray[0]
.
In the example below, the console will display e because the index is 1.
const hello = "Hello World";
console.log(hello[1]);
// Output: e
Using syntax, we can also change an item in an array using its index.
myArray[0] = 'new string';
Arrays can be nested inside other arrays. To access the nested arrays, we can use bracket notation with the index value.
const nestedArray = [[5], [8, 10]];
console.log(nestedArray[1]); // Output: [8, 10]
We can check how many elements are in an array with the .length
property.
console.log(array.length);
const students = ["John", "Ana", "Peter", "Noah"];
console.log(students.length);
// Output: 4