How is "name-to-name" a reserved word in JavaScript?

Note. This question refers to the book "JavaScript: The Good Parts" written by Doug Crockford. When I read the chapter on objects, I came across the following statement:

The quotation marks around the property name in the object literal are optional if the name is a legal JavaScript name and not a reserved word. Thus, quotation marks are required around "first-name" , but are optional around "first_name" .

And the following is an example of the object literal presented in the book:

 var stooge = { "first-name": "Jerome", "last-name": "Howard" }; 

Now I could misinterpret the text here, but it seems to me that Mr. Crockford says that first-name (with a hyphen) is a reserved word, while first_name (with an underscore) is not. If so, I do not understand how the former can be a reserved word. I did not find another explanation in the book why this is so. Can someone explain?

+6
source share
1 answer

This is not a reserved word. Without quotes, javascript will interpret the character - as a subtraction operator, try to perform the operation and fail.

One of the reasons for this is that javascript prefers to ignore spaces whenever possible. Thus, 2 - 3 coincides with 2-3 .

Enclosing everything in quotation marks makes js be interpreted as just another character, not an operator.

+13
source

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


All Articles