Multidimensional Arrays and Their Traversal in JavaScript

Topic Overview

Welcome to today's session on "Multidimensional Arrays and Their Traversal in JavaScript". Multidimensional arrays are types of arrays that store arrays at each index instead of single elements. They allow us to create complex data structures that can model various real-life scenarios. Our goal today is to strengthen your foundational knowledge of multidimensional arrays and how to handle them effectively in JavaScript.

Creating Multidimensional Arrays

To construct a multidimensional array in JavaScript, we use arrays of arrays. Here is an example to demonstrate how to create and work with 2D static arrays:

let array = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

console.log(array);
// Outputs: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]

Indexing in Multidimensional Arrays

All indices in JavaScript arrays are 0-based. In a 1-dimensional array, the [n] notation is used to access the (n+1)th element. For example, in the array ['a', 'b', 'c'], to access the element 'b', you would use array[1] since indices are zero-based.

For multidimensional arrays, each element is itself an array. Therefore, you can access an entire row (inner array) or a specific element within that row. Let's say you want to access the first row and the second element within that row:

let array = [
    ['a', 'b', 'c'],
    ['d', 'e', 'f'],
    ['g', 'h', 'i']
];

let row1 = array[0]; // Accessing the first row
let item = row1[1]; // Accessing the second element in the first row

console.log(item);  // Outputs: 'b'

Here, row1 = array[0] gets the first row, and item = row1[1] gives us the element 'b', which is the second element in the first row. Note that this is equivalent to directly accessing (array[0])[1], or array[0][1] for short:

let array = [
    ['a', 'b', 'c'],
    ['d', 'e', 'f'],
    ['g', 'h', 'i']
];

// Accessing an element directly
console.log(array[0][1]);  // Outputs: 'b'

In this case, array[0] refers to the first inner array, and [1] refers to the second element of that array.

It's also important to note that if you try to access an index that is out of bounds, it does not throw an error but returns undefined:

let array = [
    ['a', 'b', 'c'],
    ['d', 'e', 'f'],
    ['g', 'h', 'i']
];

console.log(array[3]);        // Outputs: undefined
console.log(array[0][5]);     // Outputs: undefined
console.log(array[3][5]);     // Throws a TypeError

In this example:

  • array[3] tries to access the fourth row, which does not exist, so it returns undefined.
  • array[0][5] tries to access the sixth element in the first row, which also does not exist, so it returns undefined.

However, console.log(array[3][5]) attempts to access a property of undefined, which throws a TypeError.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal