Last active
September 26, 2017 14:50
-
-
Save Tahseenm/7b2d98cfd916c9a8bb65062e97a92327 to your computer and use it in GitHub Desktop.
Javascript Undefined
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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