1

Had an error in some code this morning but I was curious as to why this parses at all.

How does this code parse?

It is missing a comma on the forth and fifth line.

var board = [
    [0, 0, 0, 0,  0,  0],
    [0, 0, 0, 0,  0,  0],
    [0, 0, 0, 0,  0,  0]
    [0, 'x', 0, 0,  0,  0]
    [0, 0, 0, 0,  0,  0]
]

Edit: It returns:

[
    [0,0,0,0,0],
    [0,0,0,0,0],
    undefined
]

My question is why does this parse, and why does undefined appear as the third element in the array?

If this is a duplicate, question can you post a link to the duplicate below.

ANSWER: The answer is: this evaluates to an array [0, 0, 0, 0, 0, 0] and the line after acts as an index lookup on that array.

For example: array[0, 'x', 0, 0, 0, 0]

which then returns undefined

silent-tiger
  • 548
  • 6
  • 20
  • It simply will be called like an array within an array. That is to say, access array B inside of array A. – Obsidian Age Jul 09 '18 at 02:09
  • It doesn't throw an error, but I can't access e.g. `board[2][0]`, which I should be able to. The highest indices I can access are `board[1][5]`. – Tim Biegeleisen Jul 09 '18 at 02:12
  • if you do a `console.log(board)`, you will notice there is only two elements in the array with a length of 3, and third element is undefined – Isaac Jul 09 '18 at 02:15
  • So the reason is: `[0, 0, 0, 0, 0, 0][0, 'x', 0, 0, 0, 0]` gives you `0`, and `[0, 0, 0, 0, 0, 0]` of `0` is undefined, thats why third element is undefined – Isaac Jul 09 '18 at 02:19
  • 3
    The comments so far have been confusing. The line in the middle — `[0, 0, 0, 0, 0, 0]` — is a regular array, but the line after that — `[0, 'x', 0, 0, 0, 0]` — accesses an index of the array. Since index (or property) access expects one expression, `0, 'x', 0, 0, 0, 0` gets evaluated as `0` (the last comma-separated expression), due to the [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator). You end up with `[0, 0, 0, 0, 0, 0][0]` or `0`. The same thing repeats for the line after that, and you end up with `0[0]`, or `undefined`. – Sebastian Simon Jul 09 '18 at 02:19

0 Answers0