Steve Teale
Steve Teale

Reputation: 219

var name and window.name

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.

Upvotes: 9

Views: 2077

Answers (2)

Ry-
Ry-

Reputation: 225263

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

Upvotes: 5

Matt Coughlin
Matt Coughlin

Reputation: 18906

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.

Upvotes: 7

Related Questions