Note: This question pertains to the book 'JavaScript: The Good Parts' written by Doug Crockford. As I was reading a chapter on Objects, I came across a statement as follows:
The quotes around a property's name in an object literal are optional if the name would be a legal JavaScript name and not a reserved word. So quotes are required around
"first-name"
, but are optional around"first_name"
.
And the following is the example of an object literal provided in the book:
var stooge = {
"first-name": "Jerome",
"last-name": "Howard"
};
Now, I might have misinterpreted the text here but to me it seems like Mr. Crockford is saying first-name
(with the hyphen) IS a reserved word whereas first_name
(with the underscore) is not. If that is the case, I don't understand how the former can be a reserved word. I found no other explanation in the book why this is. Can someone please explain?
It is not a reserved word. Without the quotes, javascript will interpret the -
character as a subtraction operator, attempt to perform the operation, and fail.
One reason for this is that javascript prefers to ignore whitespace whenever it can. Thus 2 - 3
is the same as 2-3
.
Putting the whole thing in quotes causes the js to interpret as just another character, not an operator.