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.

+3


source to share


3 answers


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);

}());

      

+6


source


'name' is the predefined name of implementation-dependent JavaScript objects, methods, or properties, you should avoid using this as a variable name, although this is not a reserved word and may work in some browsers



+3


source


name

is a reserved word, among many other words. You can see the full list here to view all reserved words.

They act like different functions, methods, etc. For example, you cannot name a function "function".

-2


source







All Articles