Skip to content Skip to sidebar Skip to footer

Property Names With Spaces In Object Literals

I'm just wondering, with the 'one', 'two', 'three' stuff, could there be a space? So instead of 'one' it could be 'one meow'? var meow = { one: function (t) { return 'a'

Solution 1:

Sure, there can be spaces in property names, but then you have to enclose them in ":

var meow    = {
            "one meow": function (t) { return "a"; },
            two:        function (t) { return "b"; },
            three:      function (t) { return "c"; }
            };

When you want to access that property later, use the bracket syntax:

console.log( meow["one meow"]() );

Solution 2:

Yes, but you can no longer access the property as meow.one mewo, instead you need to use the bracket syntax: meow['one mewo'].

Similarly, when you define the object, you need to quote the keys:

var meow = {
  'one meow'  : function (t) { return "a"; },
  two         : function (t) { return "b"; },
  'three meow': function (t) { return "c"; }
};       

Post a Comment for "Property Names With Spaces In Object Literals"