Earlier we mentioned that arrays can store other arrays. When an array contains another array it is known as a nested array. Examine the example below:
const nestedArr = [, [2, 3]];
To access the nested arrays we can use bracket notation with the index value, just like we did to access any other element:
const nestedArr = [, [2, 3]]; console.log(nestedArr); // Output: [2, 3]
nestedArr will grab the element in index 1 which is the array
Then, if we wanted to access the elements within the nested array we can chain, or add on, more bracket notation with index values.
const nestedArr = [, [2, 3]]; console.log(nestedArr); // Output: [2, 3] console.log(nestedArr); // Output: 2
In the second
console.log() statement, we have two bracket notations chained to
nestedArr. We know that
nestedArr is the array
[2, 3]. Then to grab the first element from that array, we use
nestedArr and we get the value of
Let’s make a nested array! Create a variable
numberClusters. Assign as its value an array with three array elements.
2in that order.
4in that order.
6in that order.
Awesome, you made a nested array! Now declare a variable named
target using the
const keyword and assign to access the element