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);
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With