Arrays
Arrays in JavaScript are a special type of object. They resemble Python Lists (an ordered and changeable collection, allowing duplicate members and members of different types).
const numbers = [1, 2, 2, "three", 4]; console.log(numbers); console.log(typeof numbers);
You can use the bracket notation to access and modify the array elements.
const numbers = [1, 2, 3, 4]; for (let i = 1; i < numbers.length; i++) { numbers[i] = numbers[i] + numbers[i - 1]; } console.log(numbers);
You can create an empty array and then add values to it:
const numbers = []; numbers[0] = 10; numbers[1] = 11; numbers.push(12); numbers.pop(); numbers.push(13); console.log(numbers);
Array constructor syntax
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 = [];
Madness: In an array, you can leave some elements undefined!
const numbers = [, 2, , 4, ]; for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); }
Note how the trailing comma does not denote an
undefined
element!
Allowing undefined elements leads to more annoying behaviors.
const numbers = []; numbers[99] = "hundred"; console.log(numbers.length); console.log(numbers[0]); console.log(numbers[99]); console.log(numbers[100]);
length
is calculated as one more than the highest index!
And the craziest thing is that you can overwrite the length
property!
const numbers = [1, 2, 3, 4]; numbers.length = 0; console.log(numbers[0]); console.log(numbers[1]);
Destructuring Arrays
Convenient syntax for fetching multiple elements:
const numbers = [10, 20, 30, 40]; // let first = numbers[0]; // let second = numbers[1]; let [first, second] = numbers; console.log(first, second);
You can even do this:
const numbers = [10, 20, 30, 40]; let [first, second, ...others] = numbers; console.log(first, second, others);
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]);
Array object comes with many useful built-in operations. We will explore some of these in future lectures. For the impatient, please visit Array on MDN web docs