Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the variable "name" doesn't work with a JS object

The behaviour can be seen in this little snippet (execute it as a global script):

var name = {}; name.FirstName = 'Tom'; alert(name.FirstName); 

The alert yields undefined in Chrome but works in IE and Firefox. I also get a weird value when I do

alert(name); 
like image 704
Pialy Tapaswi Avatar asked May 09 '12 20:05

Pialy Tapaswi


People also ask

Can we use in variable name in JavaScript?

JavaScript has only a few rules for variable names: The first character must be a letter or an underscore (_). You can't use a number as the first character. The rest of the variable name can include any letter, any number, or the underscore.

Which variable name is not a valid in JavaScript?

For example, break or boolean variable names are not valid. JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.

Why does my variable show it's deprecated?

If a variable that is specified with the deprecated attribute is used, the compiler issues a warning message to indicate that the variable is not recommended to be used.

Can function name and variable name be same in JavaScript?

Variables and functions share the same namespace in JavaScript, so they override each other. if function name and variable name are same then JS Engine ignores the variable. With var a you create a new variable. The declaration is actually hoisted to the start of the current scope (before the function definition).


1 Answers

window.name has a special purpose, and is supposed to be a string. Chrome seems to explicitly cast it to a string, so var name = {}; actually ends up giving the global variable name (i.e. window.name) a value of "[object Object]". Since it's a primitive, properties (name.FirstName) won't "stick."

To get around this issue, don't use name as a global variable.

like image 55
Dagg Nabbit Avatar answered Sep 22 '22 06:09

Dagg Nabbit