What happens with this rather peculiar JavaScript syntax

The following JavaScript code:

alert(2 .x); 

'Undefined' warnings (see here: http://jsfiddle.net/Rp4wk/ )

(Note: The space between "2" and ".x" is assumed)

A simple question: why? Especially if the following syntax errors exit:

 alert(2.x); alert(2. x); 

Is anyone

+4
source share
1 answer

. - operator. 2 is a number. x is the name (property).

A floating-point numeric constant must not have embedded spaces. So 2 .x is an expression that invokes the constant 2 to advance to the Number object, and then considers a property called "x". Of course, there are none, so the value is undefined .

You can get the same effect more explicitly with

 alert((2).x); 

note that

 alert("Hello".x); 

somewhat similar: in this case it is not a numeric constant, but a string constant. This is less strange because there is no syntactic ridiculous business, but otherwise the interpreter does similar things when evaluating. The string constant is first converted to a String object, and then the "x" property is retrieved.

edit - to clarify a bit, 2.x is an error, because it is parsed as a numeric constant ("2."), followed by the identifier "x", and that there is a syntax error; two values ​​adjacent to each other, such as without an intermediate operator, do not form any construct in the language.

+8
source

Source: https://habr.com/ru/post/1336805/


All Articles