Search code examples
javascriptpropertiesobject-literal

Different ways of specifying properties inside object literals in javascript


I have seen the following two ways of specifying properties for an object literal in javascript..

var a = {prop:2}

and

var a ={'prop':2}

What is the difference between these two ways..I know that the second method allows us to include whitespaces inside the property names.Is there any other advantage.?


Solution

  • No difference other than your observation about the ability to create property names that are not valid identifiers. By using quoted strings for property names, any string can be used. When accessing such properties, of course, you later have to use [ ] instead of .:

    var obj = { 'crazy property name': 100 };
    
    if (obj[ 'crazy property name' ] > 1) alert("hi");
    

    Note that strict JSON syntax requires that property names be quoted, and furthermore it requires that quoting always be done with double-quote characters.