Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are dashes allowed in javascript property names?

Tags:

javascript

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?

like image 645
xecaps12 Avatar asked Apr 01 '11 16:04

xecaps12


People also ask

Can JavaScript variable have dash?

Vars with dashes are invalid in js, so if we'll compile it with mangling, it won't violate js naming style.

Can I use dash in variable name?

Hyphens are used as subtraction and negation operators, so they cannot be used in variable names.

How do you access the hyphen in object property?

Use bracket notation to access an object property with a hyphen, e.g. obj['with-hyphen'] . There are two ways to access properties on an object - dot notation and bracket notation. If the property contains a hyphen, space, or special symbols, you have to use bracket notation.

What are property names in JavaScript?

The function name property of the javascript object is used to return the name of the function. This name property of the function is only readable and cannot be altered. The name of the function which was given when the function was created is returned by Function.name.


1 Answers

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

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

like image 95
Daniel A. White Avatar answered Oct 08 '22 01:10

Daniel A. White