Skip to content

Instantly share code, notes, and snippets.

@flaki
Created April 5, 2017 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flaki/63b7253fdbac774faf31319bc3780c04 to your computer and use it in GitHub Desktop.
Save flaki/63b7253fdbac774faf31319bc3780c04 to your computer and use it in GitHub Desktop.
Shadowing undefined
(function() {
// Won't work, 'undefined' is a property on the global object, but it's unconfigurable (not modifiable)
try {
Object.defineProperty(window, 'undefined', { value: 42 });
} catch (e) { console.log(e.toString()) }
// But 'undefined' could be still shadowed, because it's not a keyword - its name is usable as an identifier
var undefined = 42;
// foo is a non-existent property on the window object
console.log(`typeof window.foo => '${typeof window.foo}' `);
// This won't work, foo is not '42', returns false
console.log(`window.foo === undefined => ${window.foo === undefined} `);
// It is possible to get an untainted 'undefined' value by using void, which is an operator
// void always returns undefined, regardless of its operand
console.log(`window.foo === void 0 => ${window.foo === void 0} `);
// For the object property case, one could also use the 'in' operator for this test
console.log(`'foo' in window => ${'foo' in window} `);
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment