Array Basics
Arrays in JavaScript are a special type of object. They are like Python lists: the elements are ordered, you can change them, and the array can hold duplicate values and values of different types.
const numbers = [1, 2, 2, "three", 4];
console.log(numbers); // [1, 2, 2, "three", 4]
console.log(typeof numbers); // object
You can use bracket notation to read and change the elements of an array.
const numbers = [1, 2, 3, 4];
for (let i = 1; i < numbers.length; i++) {
numbers[i] = numbers[i] + numbers[i - 1];
}
console.log(numbers); // [1, 3, 6, 10]
You can create an empty array and then add values to it:
const numbers = []; // []
numbers[0] = 10; // [10]
numbers[1] = 11; // [10, 11]
numbers.push(12); // [10, 11, 12]
numbers.pop(); // [10, 11]
numbers.push(13); // [10, 11, 13]
console.log(numbers); // [10, 11, 13]
You can make an empty array using array constructor syntax:
const numbers = new Array();
But it is more common to use the array literal syntax instead:
const numbers = [];
In an array, you can leave some elements undefined.
const numbers = [, 2, , 4]; // [undefined, 2, undefined, 4]
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
Because elements can be left undefined, you can get behavior you did not expect.
const numbers = [];
numbers[99] = "hundred";
console.log(numbers.length); // 100
console.log(numbers[0]); // undefined
console.log(numbers[99]); // hundred
console.log(numbers[100]); // undefined
You can also overwrite the length property.
const numbers = [1, 2, 3, 4];
numbers.length = 0;
console.log(numbers[0]); // undefined
console.log(numbers[1]); // undefined
Destructuring Arrays
Destructuring is a convenient syntax for pulling several elements out of an array at once:
const numbers = [10, 20, 30, 40];
// let first = numbers[0];
// let second = numbers[1];
let [first, second] = numbers;
console.log(first, second); // 10 20
You can even do this:
const numbers = [10, 20, 30, 40];
let [first, second, ...others] = numbers;
console.log(first, second, others); // 10 20 [30, 40]
Multi-dimensional arrays
Use arrays of arrays for multi-dimensional arrays:
const magicSquare = [
[16, 3, 2, 13],
[5, 10, 11, 8],
[9, 6, 7, 12],
[4, 15, 14, 1],
];
// Use two bracket pairs to access an element:
console.log(magicSquare[1][2]); // 11