0

According to this page https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Reserved_Words

You can't use these reserved words as variables, but can you use them this way apperantly:

var test = {
    break : 'whatever',
    case : 'whatever',
    if : 'whatever',
    in : 'whatever'
    //etc
};

I have a fiddle here with all the values http://jsfiddle.net/9RQ9j/4/

And I get no errors either defining them or calling for instance like this

console.log(test.if)

So to me it seems possible, but is it in conflict with the javascript spec? Then it seems at least like all the browsers I have tested in (which are most) do violate the spec and allow you to use those words.

(UPDATE: seems to fail in IE 8 + possibly other IE's)

And is it even good practice?

Last question: Is this ok?

var test = {
    'break' : 'whatever',
    'case' : 'whatever',
    'if' : 'whatever',
    'in' : 'whatever'
};
2
  • 4
    the page you linked to answers the question. See the section Reserved word usage at the bottom. Commented Sep 27, 2012 at 10:50
  • Yeah I somehow managed to ignore that. However using any of the reserved words like this triggers an error in IE8 that I tested now. Maybe in other IE as well. So I assume you should to var test = {'if': 'whatever'} to be safe cross browser. But even after defining it like that you cannot call test.if, you need to do test['if'] it seems in IE8 Commented Sep 27, 2012 at 11:19

2 Answers 2

2

According to the ES5 Spec, object properties are IdentifierNames, not Identifiers, which means that they do not exclude reserved words.

Is it good practice? Probably not in general, but if it makes your code clearer, then yes.

And yes, referencing properties with a quoted string is equivalent to referencing them with the same unquoted symbol -- but the set of identifiers that you can use quoted is obviously larger than those you can use unquoted.

Sign up to request clarification or add additional context in comments.

Comments

-1

test this :

console.log(test['if']);

In JS, Array are object, so the both syntaxes are good.

1 Comment

That doesn't answer the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.