3

Why can't you call a 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 it returns an empty string?

I use Chrome.

4
  • 3
    You should be able to call a variable name. Calling name in the console is the same as accessing the name property of window. Commented Dec 12, 2014 at 15:02
  • Works fine for me in Chrome. What browser are you using? Commented Dec 12, 2014 at 15:03
  • MDN window name Commented Dec 12, 2014 at 15:04
  • Don't create so many globals and you'll be fine. Commented Dec 12, 2014 at 15:18

2 Answers 2

6

Because window.name is a magic property of window object and can hold only strings (any object, including arrays, is coerced to primitive type and becomes something like "[Object Object]"). Variables defined in global scope become properties of global object and it can cause conflicts.

You can have variable name in any nonglobal scope. Simple workaround can be to wrap your code in immediately-invoked function expression (IIFE).

(function(){

    var wrapper = document.createElement("div");

    var name = document.createElement("div");


    wrapper.appendChild(name); // workd


    document.body.appendChild(wrapper);

}());
Sign up to request clarification or add additional context in comments.

2 Comments

This is correct answer. I would also add that setting window.name automatically preforms casting to String type, so setting window.name will result in something like window.name = [object HTMLDivElement].
I have added this information. TIL: window.name can hold only strings, not other primitive types.
3

'name' is a predefined name of implementation-dependent JavaScript objects, methods, or properties, you should avoid to use this as a name for a variable, though it's not a reserved word and might work in some browsers

Comments