Introduction to Arrays in JavaScript
Code Playground is only enabled on larger screen sizes.
Array is a data structure that stores a collection of data. It is created using a pair of square brackets ([]):
let arr = ["Apple", "Orange", "Banana"];
console.log(arr); // -> [ 'Apple', 'Orange', 'Banana' ]The elements inside the array can be any data types, such as numbers, BigInt, strings, Boolean values, null, undefined, other arrays, objects, and even functions:
// prettier-ignore
let arr = [
100, // Number
999999999999999999n, // BigInt
"Qwerty", // String
null, // null
undefined, // undefined
[1, 2, 3], // Array
{ name: "John Doe" }, // Object
function doNothing() { // Function
return null;
},
];Accessing an array element
You can access an array element by specifying its index number like this:
let arr = [5, 6, 7, 8];
console.log(arr[0]); // -> 5
console.log(arr[1]); // -> 6
console.log(arr[2]); // -> 7
console.log(arr[3]); // -> 8It is important to note that the array index starts from 0, not 1, so a[0] points to the first element, a[1] points to the second element, and so on.
Alternatively, you can use the at() method. For instance,
let arr = [5, 6, 7, 8];
console.log(arr.at(0)); // -> 5
console.log(arr.at(1)); // -> 6
console.log(arr.at(2)); // -> 7
console.log(arr.at(3)); // -> 8The at() method works the same as the arr[<index>] syntax, with one small perk.
Most other programming languages offers negative indexing for arrays, which allows you to retrieve the last item in an array with arr[-1], but that is not possible in JavaScript.
So for a long time, people's solution was using the length of the array minus one (arr.length - 1), like this:
let arr = [5, 6, 7, 8];
console.log(arr[arr.length - 1]); // -> 8arr.length gives the number of elements in the array, which is 4 in this case. But remember the index starts from 0, so the index of the last item should be arr.length - 1, which gives 3.
at() method was introduced to offer an easier solution, allowing you to use negative indexes to access items from the end of the array:
let arr = [5, 6, 7, 8];
console.log(arr.at(-1)); // -> 8
console.log(arr.at(-2)); // -> 7
console.log(arr.at(-3)); // -> 6
console.log(arr.at(-4)); // -> 5Nested arrays
It is possible for you to create nested arrays by putting arrays inside an array:
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];To retrieve an element from this nested array, you need to specify two indexes, matrix[<row>][<col>].
console.log(matrix[0][1]); // -> 2
console.log(matrix[1][0]); // -> 4
console.log(matrix[2][2]); // -> 9The first index corresponds to the index of the sub-array, and the second index corresponds to the elements inside that sub-array.
let arr = new Array("Apple", "Orange", "Banana"); console.log(arr);
