object literal - How is "first-name" a reserved word in JavaScript? - Stack Overflow

Note: This question pertains to the book 'JavaScript: The Good Parts' written by Doug Crockfo

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?

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?

Share Improve this question asked Sep 17, 2013 at 16:04 BinaryCatBinaryCat 1,3002 gold badges17 silver badges32 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744496810a4577189.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信