Last active
December 9, 2015 19:38
-
-
Save kirstein/4317680 to your computer and use it in GitHub Desktop.
Undefined checks
This file contains hidden or 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
| # JavaScript undefined | |
| > The cause of headaches. | |
| > The bringer of tears. | |
| > The destroyer of functions. | |
| > The slayer of equations. | |
| ## The Problem | |
| JavaScript has a few problems. One of which being the fact that everybody can override the ```undefined``` value. | |
| This, when occurring, brings a lot of tears to developers eyes. Especially when the developer has not prepared for such an event. | |
| ## Example of the problem | |
| To display the problem i have created a simple [jsfiddle][jsfiddle] demonstration. | |
| In that [demo][jsfiddle] i will overwrite undefined value in scope and do numerous equations to check the values. Surprising results??? | |
| As the [demo][jsfiddle] clearly shows then JavaScript is uncap-able of detecting bogus ```undefined``` values. | |
| ## The cure | |
| The cure itself is simple. Use a ```typeof``` operator. | |
| Example: | |
| ``` | |
| // Keep in mind that i am not using type conversions. | |
| // Also the "quotes". | |
| if (typeof x === "undefined") { | |
| // magic | |
| } | |
| ``` | |
| ## Aftermath | |
| This issue itself is quite simple. However I've seen people failing to-do proper ```undefined``` checks for ages. | |
| I can just imagine the amount of joy a developer has when somebody, who has a sick sense of humor, preforms a successful [persistent XSS][xss] injection and overwrites ```undefined``` value in some scope... | |
| [jsfiddle]: http://jsfiddle.net/kirstein/KY4tV/ | |
| [xss]: http://en.wikipedia.org/wiki/Cross-site_scripting |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment