0

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?

Isuru Maldeniya
  • 151
  • 1
  • 7
  • What do you want to achieve by that? – Nico Haase Sep 21 '22 at 06:52
  • If you piss a comma it will create a array access, like the `a[2]` operator. There is so key `"third"` to this will be undefined. You can't use the `[]` operator on undefined – mousetail Sep 21 '22 at 06:53
  • @NicoHaase I just want to understand why this is happening and why the array is created in the second scenario. – Isuru Maldeniya Sep 21 '22 at 07:04
  • In your first snippet, `["second", 2]` is a property accessor, not an Array, just like you can do `obj["foobar"]`, except that here `,` is the [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator), which will evaluate each expressions and return the right most one, so in this case `2`. So `["first", 1]["second", 2]` is equal to `["first", 1][2]`, this is undefined. and doing `["third", 3]` tries to access the property `"3"` from this `undefined` value, which is illegal. – Kaiido Sep 21 '22 at 07:06
  • If you had only `0` has second operands that would have produced `[["f"]]`, because that's the first letter of the first letter of the string `"first"`. – Kaiido Sep 21 '22 at 07:08

1 Answers1

2

["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"
VLAZ
  • 26,331
  • 9
  • 49
  • 67