Skip to content

Instantly share code, notes, and snippets.

@Tahseenm
Last active September 26, 2017 14:50
Show Gist options
  • Save Tahseenm/7b2d98cfd916c9a8bb65062e97a92327 to your computer and use it in GitHub Desktop.
Save Tahseenm/7b2d98cfd916c9a8bb65062e97a92327 to your computer and use it in GitHub Desktop.
Javascript Undefined
/**
* Undefined cannot be assigned using window.undefined = someVal or
* undefined = someVal but can be changed using function scope.
* window.undefined is the same as window['undefined']
*
* The same example does not work with the null keyword and program throws
* a syntax error (function (null) {...})(123)
*/
;(function (undefined) {
// x is undefined
let x;
if (x === undefined) {
// Will NOT run as [undefined !== 123]
console.log('Foo');
}
if (typeof x === 'undefined') {
// Will RUN
console.log('Bar');
}
console.log(`undefined is ${undefined}`); // -> undefined is 123
})(123);
/**
* Solution
* Create a another function scope for your own code
*/
;(function (undefined) {
(function (undefined) {
'use strict';
let x;
if (x === undefined) {
// Will Run
console.log('Foo');
}
if (typeof x === 'undefined') {
// Will RUN
console.log('Bar');
}
console.log(`undefined is ${undefined}`) // -> undefined is undefined
})()
})(123);
/**
* ES5 best practice
*/
;(function (global, undefined) {
'use strict';
// App code
})(window)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment