-1

I have followed these links

How [1,2] + [4,5,6][1] = 1,25 in JavaScript

Why does [5,6,8,7][1,2] = 8 in JavaScript?

but not able to understand why the following code is undefined. My understanding is [1,2,3] will give 3, so from [1,2,3,4,5,6,7][3] will be 4 and hence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] will be [1, 2, 3, 4, 5, 6, 7, 8, 9, 10][4] that is 5. But it logs undefined.

console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10][1, 2, 3, 4, 5, 6, 7][1, 2, 3])
Kamil Kiełczewski
  • 71,169
  • 26
  • 324
  • 295
brk
  • 46,805
  • 5
  • 49
  • 71

3 Answers3

4

You are on the right track. The second and third group of [...] are a property access with bracket notation, and the 1, 2, 3 are treated as comma operators, evaluating to the last entry in the list. So your code is basically the same as:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10][7][3]

Now the seventh number in the array is 8:

 8[3]

and that does not have a "3" property.

Jonas Wilms
  • 120,546
  • 16
  • 121
  • 140
1

Breaking it down into the two steps actually executed may help. First you get an 8, a number, then you try to index it – undefined ahoy!

> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10][1, 2, 3, 4, 5, 6, 7]
8
> 8[1,2,3]
undefined
AKX
  • 123,782
  • 12
  • 99
  • 138
1

You define 1D array a=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] but you treat it as 2D array during value reading a[...][...] (the a[...] returns array element - which is number - not array). This is the mistake in idea behind your code.

a=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log( a[0][0] );
Kamil Kiełczewski
  • 71,169
  • 26
  • 324
  • 295