9

If I define a JavaScript global variable called name, does that hide the window.name property?

I ask this in the context of the Facebook JavaScript authentication API, since I noticed that having a global of that name would break it, and also since I see that window.name is used in their code.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Steve Teale
  • 219
  • 3
  • 9
  • 1
    Related: https://stackoverflow.com/questions/10523701/using-the-variable-name-doesnt-work-with-a-js-object – melpomene Jun 07 '19 at 09:43

2 Answers2

7

If name is a global variable, then name and window.name are equivalent.

Global variables and functions are members of the global object. In browsers, the global object contains a window member whose value is the global object.

Matt Coughlin
  • 18,666
  • 3
  • 46
  • 59
5

If you declare a variable in the global scope with var, it will create a property on the global object or write to an existing one (like name):

var name = 5;
console.log(window.name === '5');  // true
console.log(name === '5');  // true
console.log(Object.getOwnPropertyDescriptor(window, 'name'));
    // object with get and set

var foo = 6;
console.log(Object.getOwnPropertyDescriptor(window, 'foo'));
    // object with value

Object.defineProperty(window, 'bar', {
    writable: false,
});

var bar = 7;  // throws in strict mode

var baz;
console.log('baz' in window);  // true

If you declare it with let or const, it won’t:

const name = 5;
console.log(window.name);  // likely an empty string
console.log(name === 5);  // true
console.log(Object.getOwnPropertyDescriptor(window, 'name'));
    // same as var

const foo = 6;
console.log(window.foo);  // undefined
console.log(Object.getOwnPropertyDescriptor(window, 'foo'));
    // undefined

Object.defineProperty(window, 'bar', {
    writable: false,
});

const bar = 7;  // succeeds

let baz;
console.log('baz' in window);  // false
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • @Xufox: Thanks! I appear to have completely missed the “hide” part of this question. Updated. – Ry- Mar 10 '17 at 04:56