6️⃣

5.6 2D Arrays

5.6 2D Arrays

JavaScript does not provide the multidimensional array natively.

However, you can create a multidimensional array by defining an array of elements, where each element is also another array.

For this reason, we can say that a JavaScript multidimensional array is an array of arrays. The easiest way to define a multidimensional array is to use the array literal notation.

To declare an empty multidimensional array, you use the same syntax as declaring one-dimensional array:

let activities = [];

The following example defines a two-dimensional array named activities:

let activities = [
    ['Work', 9],
    ['Eat', 1],
    ['Commute', 2],
    ['Play Game', 1],
    ['Sleep', 7]
];

Here's what the code is doing conceptually:

In the activities array, the first dimension represents the activity and the second one shows the number of hours spent per day for each.

To show the activities array in the console, you use the console.table() method as follows:

console.table(activities);

// output:
┌─────────┬─────────────┬───┐
 (index)01├─────────┼─────────────┼───┤
0'Work'91'Eat'12'Commute'23'Play Game'14'Sleep'7└─────────┴─────────────┴───┘

Practice

You can add practice problems here if you want. Follow the format below.

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.