Isuru Maldeniya
Isuru Maldeniya

Reputation: 348

Is there a minimum number of arrays inside a multi dimentional array in javascript?

When I try to create a multidimensional array, I accidentally forgot to add , in between each sub-array.

const multi = [["first", 1]["second", 2]["third", 3]["fourth", 4]];

And I found that with browser console it gives an error in some occasions, and it declares the array in some occasions. Below are what I tried with Firefox web browser console,

First, I try to put , after the first sub-array.

const multi2 = [["first", 1], ["second", 2]["third", 3]["fourth", 4]]; 

return ==> Uncaught TypeError: ["second", 2][3] is undefined

But if I add , after the second sub-array, it will declare the multidimensional array.

const multi3 = [["first", 1], ["second", 2], ["third", 3]["fourth", 4]]; 

And when I try multi3 on console it will display the array and the value of the 3rd element is undefined. And the length of mult3 is 3. Can you please explain why this is happening?

Upvotes: 0

Views: 40

Answers (1)

VLAZ
VLAZ

Reputation: 29041

["hello", "world"] is an array. [1] accesses a property called 1, therefore:

console.log( ["hello", "world"][1] ); //result: "world"

You can keep chaining the accessors

console.log( ["hello", "world"][1][2] ); //result: "r"

If any part before the end of the chain produces undefined you would get an error because you cannot get a property of it:

console.log( ["hello", "world"][42][2] ); //error


As for ["hello", "world"][1, 2] it uses the comma operator and is equivalent to ["hello", "world"][2]:

console.log( (1, 2) ); //result: 2

console.log( ["a", "b", "c", "d"][1, 2] ); //result: "c"

Upvotes: 3

Related Questions