Why is 3 [4,2] evaluating to undefined in JS?

For some, maybe illogical or derisive, I can tell you about the JS results, for example:

// Coercing to string and concatenating
3 + [4,2]
'34,2'

// Coercing and doing proper math
4 - [2]
2

// Or failing miserably
3 - [4,2]
NaN

      

But why 3[4,2]

is it priced before undefined

? At least the examples above are doing operations ( something ). In a related note, ironically, it [4,2]3

causes an error SyntaxError: Unexpected number

.

What's going on here?

Context . Passed morning search and distribution of errors in which the label was absent ,

(comma) array of numbers and combinations of nested arrays: [1, 2, 3 [4, 2], 5, [8], 7]

.

+3


source to share


1 answer


Expression

3[4,2]

      

assessed as

(new Number(3))[4, 2]

      

property search operation. The expression 4,2

is an example of a comma operator, and its value is the latest in subexpressions list 2

.



The runtime-generated Number instance does not have property "2", so the result undefined

.

The language treats operators .

and is []

almost the same, although it .

gets confused with the grammar of markers for numeric literals. The left side is converted to an object (if possible, and when undefined

you get the familiar message "Can not read property foo of undefined"). The property value is then fetched if it exists.

So for example

3["valueOf"]

      

not undefined

: this is a function reference Number.prototype.valueOf

.

+8


source







All Articles