56

Can a reserved word be used as an object's property name?

This issue was raised indirectly in a previous Stack Overflow question: Browser support for using a reserved word as a property name in JavaScript. The answer seemed general consensus by Alex Wayne:

You can use those words, but only as strings and not shorthand properties.

foo['class']; // cool
foo.class;    // not cool

While I think that they are probably more knowledgeable than me in this area and it is probably a bad idea to use reserved words in some situations, I think their conclusion is wrong based on two points:

  • testing of the reserved words using them as a "shorthand" properties

  • the HTMLFormElement makes it impossible not to use reserved words in "shorthand"

First, using the reserved word list, each was added as a property to an Object and HTMLElement, both as obj["word"] and obj.word, and then retrieved as obj["word"] and obj.word. In each of the 63 cases all eight tests worked correctly.

Second, the HTMLFormElement necessitates this works because it retrieves in its elements using shorthand notation. If <input name='typeof' value='scalar' /> is an element of a form, then form.typeof == "scalar".

From my experience, reserved words are usually data inflicted (e.g. a column named "private"), not program inflicted. As such they contaminate JSON objects, and from there input, and from there the HTMLFormElement. Simply put, without a huge amount of (IMHO unnecessary) work, it's impossible to keep reserved words not being forced to work correctly in shorthand.

It seems to me these real problems:

  • care needs to be taken not to conflict with existent properties, not reserved words

  • (many if not all) variables cannot be reserved words

  • use of reserved words as properties can be (but are not necessarily) confusing

Is this conclusion correct then, that reserved words as property names, and accessing them either as strings or shorthand, is just fine - as long as a little common sense is applied to the situation?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
cc young
  • 18,939
  • 31
  • 90
  • 148
  • What does it mean `form.typeof`? I mean, how is it related to HTMLFormElement? A property of a JS object can be accessed in at least two ways `['prop']` and with the dot notation `.prop`. And this has nothing to do with HTMLFormElement or the DOM API or anything else. `form['typeof']` is absolutely normal – d.k Jan 19 '17 at 11:07
  • I think anybody’d want to ensure they don’t have 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', or 'valueOf' being used as property names — unless the object’s explicitly created with a null prototype. Or unless they’re intentionally using those to monkeypatch the prototype. At least for 'constructor' it’s imaginable somebody could end up naively trying to use it as a normal property name — with some arbitrary value — and be surprised later when trying to do something with the value of it. See https://stackoverflow.com/a/21320309/441757. – sideshowbarker Dec 30 '19 at 08:31

4 Answers4

57

In ECMAScript, starting from ES5, reserved words may be used as object property names "in the buff". This means that they don't need to be "clothed" in quotes when defining object literals, and they can be dereferenced (for accessing, assigning, and deleting) on objects without having to use square bracket indexing notation.

That said, reserved words may still NOT be used as identifier names. This is stated quite unambiguously in the spec and is stated somewhat emphatically here (if you don't want your eyes to bleed by having to read the actual language spec)...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words

The following are keywords and may not be used as variables, functions, methods, or object identifiers, because ECMAScript specifies special behavior for them:

UIZE
  • 654
  • 7
  • 2
  • How then, can we minify scripts like bootstrap_multiselect.js which use constructs like $tag = $('').attr({ value: option.value, label: option.label || option.value, title: option.title, class: option.class, selected: !!option.selected, disabled: !!option.disabled }); – Farhad Oct 06 '16 at 08:17
  • 1
    * reserved words may still NOT be used as **identifier names***. Did you mean **identifiers**? Because from what I have read here and at the page linked, it looks like they MAY be used as identifier names (IdentifierNames) and not as identifiers. – d.k Jan 19 '17 at 11:51
  • 1
    "_ReservedWord_ is an enumerated subset of _IdentifierName_. The syntactic grammar defines _Identifier_ as an _IdentifierName_ that is not a _ReservedWord_". Clear as mud. [source](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-names-and-keywords) – David Gilbertson Jan 20 '17 at 23:03
  • 1
    Had a curious bug where I was counting instances of keywords in a string, and was testing for the first occurance with `if (typeof key [token]==="undefined")...` - false positive for constructor which is "function". Ended up using two arrays one for keys, one for values, which suited my needs in other ways.(saved calling Object.keys later) – unsynchronized Jan 16 '19 at 21:48
8

Yes, it can be used.

Just small remark, if you use YUI compressor you have to put property name which is equal to one of js reserved words in quotes.

For example, this won't compress

var a = { case : "foo"}; // syntax error, "invalid property id"
a.for = "bar"; // syntax error, "missing name after . operator"

This will do

var a = { "case" : "foo"}; //OK
a["for"] = "bar"; //OK

Here is Online JavaScript/CSS Compression Using YUI Compressor where this can be tested.

humkins
  • 9,635
  • 11
  • 57
  • 75
8

I'm not quite sure what the point is you want to make, so the only answer I can give is: Yes, it's ok to use reserved words as property names.

(However two small remarks: foo["class"] is ok, not foo[class]. And any way you should be using form.elements["xyz"] and not form.xyz to access an element named xyz.)

MrWhite
  • 43,179
  • 8
  • 60
  • 84
RoToRa
  • 37,635
  • 12
  • 69
  • 105
  • 3
    _absolutely_ agree on using `form.elements['abc']` instead of `form.abc` - but the point is javascript browser supports `form.abc` by definition. fixed typo above. through google and the quality, stackoverflow is becoming a highly regarded reference. when I referenced, did not makes sense, so "trying to set the record straight" - and thinking I might be wrong at that. – cc young Aug 11 '11 at 08:57
  • The non-JSR223 implementation of the Mozilla Rhino JavaScript engine does this when the script throws a JavaException. If you need to do special logic to handle it, you need to check `exception.javaException["class"].name` to see if it matches the Java class name of the specific exception you're looking for. – sworisbreathing Nov 02 '11 at 15:58
  • Why should you use `foo["xyz"]` over `foo.xyz`? I see no reason to favour one over the other. The first one just adds a lot of noise and is only useful is you're using a reserved word or a variable as a key. – cdmckay Jul 24 '13 at 00:34
  • @cdmckay I didn't say that. – RoToRa Jul 24 '13 at 07:40
3

Yes, in most browsers (including IE9+)

There's actually an entry in the Kangax compatibility table for "Reserved words as property names"

http://kangax.github.io/compat-table/es5/#test-Object/array_literal_extensions_Reserved_words_as_property_names

David Gilbertson
  • 4,219
  • 1
  • 26
  • 32