This question already has an answer here:
- Using the variable “name” doesn't work with a JS object 3 answers
Why is it that assigning a DOM element to the global variable "name
" doesn't work ?
This question already has an answer here:
Why is it that assigning a DOM element to the global variable "name
" doesn't work ?
Most "globals" in JavaScript when running in a browser are actually properties of the window
object (of type Window
).
But Window
already has a name
property, so any attempt to assign a non-string to it is going to lead to conversion to a string: the type of the assigned object will not be maintained.
While name by itself is a property of the window object, you may still use name with another object as follows:
var obj2 = { "s1": "spring", "s2": "summer", "s3": "fall", "s4":"winter"};
obj2.name = obj2["s4"];
console.log("Name: " + obj2.name);
obj2.favoriteWeather = obj2.name;
console.log("Favorite season: " + obj2.favoriteWeather);
Resource: MDN Talk: Reserved_Words