JavaScript - Why can't I call a variable "name"?
Why can't you call the variable in JS "name"?
var wrapper = document.createElement("div");
var name = document.createElement("div");
wrapper.appendChild(name); // TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
document.body.appendChild(wrapper);
When I type "name" in the console in a new tab, does it return an empty string?
I am using Chrome.
source to share
Because it window.name
is a magic property of an object window
and can only contain strings (any object, including arrays, is coerced into a primitive type and becomes something like "[Object Object]"
). Variables defined in the global scope become properties of the global object and can cause conflicts.
You can have a variable name
in any non-local mode. A simple workaround might be to wrap your code in an Expressed Function Expression (IIFE).
(function(){
var wrapper = document.createElement("div");
var name = document.createElement("div");
wrapper.appendChild(name); // workd
document.body.appendChild(wrapper);
}());
source to share