Multidimensional Arrays and Their Traversal in TypeScript
Topic Overview
Welcome to today's session on "Multidimensional Arrays and Their Traversal in TypeScript". Multidimensional arrays in TypeScript are similar to those in other programming languages but with the added benefit of type safety. These arrays store arrays at each index instead of single elements, enabling 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 TypeScript.
Creating Multidimensional Arrays
To construct a multidimensional array in TypeScript, we utilize arrays of arrays, incorporating type annotations to specify data types clearly. Here is an example demonstrating how to create and work with 2D static arrays:
Indexing in Multidimensional Arrays
All indices in TypeScript 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. 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:
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]:
If you try to access an index out of bounds, it returns undefined:
In the above example, we use the optional chaining (?.) operator to safely attempt to access nested properties without causing a runtime error. Normally, trying to access an out-of-bounds index like array[3][5] would throw a TypeError because array[3] is undefined, and you're attempting to access a property [5] on undefined. By using array[3]?.[5], the optional chaining operator ?. ensures that if array[3] is undefined, the expression will short-circuit and return undefined immediately, avoiding any error. This is particularly useful when dealing with multidimensional arrays where the index might not always exist.
