0

can i use dash on the end of javascript object property name like this. I could not find in any documentation that this is not valid but i got some strange results when trying to access value myProp- in this case.

var myObject = {"myProp-":"myValue"};

i can only access to this value like this myObject["myProp-"] and i would like to access like

myObject.myProp-

but i got " SyntaxError: Unexpected token } "

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
user12733
  • 161
  • 1
  • 1
  • 11
  • Yes you can, but in this case you have to access it like this: `myObject["myProp-"]`. There are a lot of [info](https://www.google.by/search?q=javascript+object+valid+keys&aq=1&oq=javascript+object+vali&aqs=chrome.2.57j0l3j62l2.10197j0&sourceid=chrome&ie=UTF-8#hl=en&sclient=psy-ab&q=javascript+object+valid+keys&oq=javascript+object+valid+keys&gs_l=serp.12...0.0.0.152521.0.0.0.0.0.0.0.0..0.0...0.0...1c..8.psy-ab.0szo_YiWUGs&pbx=1&bav=on.2,or.r_qf.&bvm=bv.44770516,d.Yms&fp=94aab36a3e6c7776&biw=1280&bih=923).. – dfsq Apr 04 '13 at 15:19
  • 1
    More info on variable names validity : http://stackoverflow.com/questions/1661197/valid-characters-for-javascript-variable-names – Laurent S. Apr 04 '13 at 15:19
  • why don't you want to use the bracket syntax? – Jamie Hutber Apr 04 '13 at 15:20
  • 1
    @dfsq OP said he doesn't want to use brackets.... – Jamie Hutber Apr 04 '13 at 15:21
  • 1
    I don't think anything with a dash is a valid variable name becaue JS thinks it's a minus sign 1-2 (one minus two). You can use it as part of a string when surrounded by quotes and then use that string as an identifier but that's the only way you can use it. – HMR Apr 04 '13 at 15:24

2 Answers2

5

You'll have to use bracket notation instead of dot notation:

myObject["myProp-"]
chrx
  • 3,344
  • 1
  • 14
  • 17
  • Just saw [this.](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects) – user12733 Apr 04 '13 at 15:32
  • @chrx Have you any idea briefly why we need to use square bracket instead of we already define in '{' ? – VjyV Nov 25 '16 at 10:04
1
var myObject = {"myProp-":"myValue", "foo": "bar" };

myObject.foo;
myObject["foo"]; // these are equivalent

myObject.myProp-; // syntax error
myObject["myProp-"]; // this is fine

var key = "myProp-";
myObject[key]; // this works as well (dynamic index)
myObject.key; // undefined

Bracket notation are dot notation are equivalent.

Halcyon
  • 56,029
  • 10
  • 87
  • 125