Are dashes allowed in javascript property names?

Javascript

Javascript Problem Overview


I was looking at http://docs.jquery.com/Plugins/Authoring#Defaults_and_Options to create a simple plugin for jQuery. Following the section about options and settings, I did the following, which didn't work (the script quit when it encountered the setting).

var settings = {
    'location' : 'top',
    'background-color': 'blue'
}
...
$this.css('backgroundColor', settings.background-color); // fails here

Once I removed the dash from the background color, things work properly.

var settings = {
    'location' : 'top',
    'backgroundColor': 'blue' // dash removed here
}
...
$this.css('backgroundColor', settings.backgroundColor); 

Am I missing something, or are the jQuery docs wrong?

Javascript Solutions


Solution 1 - Javascript

no. the parser will interpret it as the subtract operator.

you can do settings['background-color'].

Solution 2 - Javascript

Change settings.background-color to settings['background-color'].

Variables cannot contain - because that is read as the subtract operator.

Solution 3 - Javascript

Dashes are not legal in javascript variables. A variable name must start with a letter, dollar sign or underscore and can be followed by the same or a number.

Solution 4 - Javascript

You can do something like this:

var myObject = {
  propertyOne: 'Something',
  'property-two': 'Something two'  
}

for (const val of [  myObject.propertyOne,  myObject['propertyOne'],
  myObject['property-two']
  ]){
  console.log(val)
}

Solution 5 - Javascript

You can have dashes in strings. If you really wanted to keep that dash, you'd have to refer to the property using brackets and whatnot:

$this.css('backgroundColor', settings['background-color']);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionxecaps12View Question on Stackoverflow
Solution 1 - JavascriptDaniel A. WhiteView Answer on Stackoverflow
Solution 2 - Javascriptgen_EricView Answer on Stackoverflow
Solution 3 - JavascriptJaredParView Answer on Stackoverflow
Solution 4 - JavascriptPrimoz RomeView Answer on Stackoverflow
Solution 5 - JavascriptsdleihssirhcView Answer on Stackoverflow