Last active
August 29, 2015 14:09
-
-
Save nulayuhz/7fb5c7cad31d22b2b5fd to your computer and use it in GitHub Desktop.
creating DOM elements with ID creates global variables
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
https://github.com/getify/You-Dont-Know-JS/blob/master/types%20&%20grammar/apA.md#appendix-a-mixed-environment-javascript | |
Host Objects | |
Global DOM Variables | |
what may be lesser common knowledge is that (because of legacy browser behavior) | |
creating DOM elements with id attributes creates global variables of those same names. | |
For example: | |
<div id="foo"></div> | |
if (typeof foo == "undefined") { | |
foo = 42; // will never run | |
} | |
console.log( foo ); // HTML element | |
"You're perhaps used to managing global variable tests (using typeof or in window checks) | |
under the assumption that only JS code creates such variables, but as you can see, the | |
contents of your hosting HTML page can also create them, which can easily throw off | |
your existence checks logic if you're not careful. | |
This is yet one more reason why you should, if at all possible, avoid using global variables, | |
and if you have to, use variables with unique names that won't likely collide. But now you | |
know you need to make sure not to collide with the HTML content as well as any other code." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/getify/You-Dont-Know-JS/blob/master/types%20&%20grammar/apA.md#appendix-a-mixed-environment-javascript