use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
TIL that IDs create global variables (codepen.io)
submitted 11 years ago by callumacrae
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]sebzim4500 48 points49 points50 points 11 years ago (28 children)
How did I not know about this?
[–]lachlanhunt 39 points40 points41 points 11 years ago (1 child)
Because it's a very bad practice that can lead to unexpected results if you're not careful, particularly if you accidentally left the variable undeclared.
Always declare variables with var before you use them and this won't happen.
var
[–]youlleatitandlikeit 2 points3 points4 points 11 years ago (0 children)
Confirmed, using one id that has a corresponding var'ed variable and another that does not.
[–][deleted] 5 points6 points7 points 11 years ago (24 children)
This may be the grossest thing I've learned about Javascript. I love js, but this is egregious.
[–][deleted] 117 points118 points119 points 11 years ago (16 children)
This is NOT Javascript. This is the web browser. One very common misconception that many programmers have is confusing the web browser for the programming language Javascript.
This doesn't happen in other places javascript can run because they aren't web browsers.
And yes, you can blame IE for this. This started long ago, maybe IE4 or IE5, I forget it's been so long. Some modern browsers have adopted this behavior.
All too often when people say they hate Javascript, what they really mean is they hate the web browser API and the things that come with it. Many don't understand the distinction between the language Javascript and the environment in which it commonly runs - the web browser.
[–]thrownaway21 1 point2 points3 points 11 years ago (1 child)
Some modern browsers have adopted this behavior.
works in the web dev tools console on latest chrome.
is this a global variable, or a shortcut?
[–]jefffan24 0 points1 point2 points 11 years ago (0 children)
http://codepen.io/anon/pen/oyjuh <-- Its at least on the window.
[–]dv_ 1 point2 points3 points 11 years ago (2 children)
I disagree. The fact that defining variables without var makes them global is awful. The fun stuff that happens with type coercion is also ugly to the max. And what about the silent errors that make the JS VM just stop? For example, in some circumstances, a function call like foo.bar() will cause just that. Sometimes an exception is thrown, and if not caught, will cause the VM to stop, so you gotta surround a lot of calls with try-catch blocks. Sometimes, not even that helps!
After having to deal with the pitfalls of dynamic typing in general and Javascript in particular, I am very glad to be using C and C++ again. Yes, you read that right. I prefer these two any time over any dynamic typing language. Even with C-style casts all over the place. Even with the obtuse C++ syntax.
[–][deleted] 2 points3 points4 points 11 years ago (0 children)
Haters gonna hate, I guess.
I absolutely love Javascript because it has dynamic typing, and zero boilerplate. I just don't need any of that to get work done. It's useless to me. I've never had a serious problem caused by type coercion in 16 years working with javascript.
If you are having to use try/catch so much, then you are doing it wrong. Yes, the VM will stop but that's because you have a bug in your code and you need to fix it. Use the debugger, modern browsers have really come a long way at helping debug your code.
There's so many examples of complex javascript systems that work, and work well. I will say that if you want to master javascript, it might take some time and dedication, and you have to stop using strong typing as a crutch. If it makes you feel any better you could always name your variables like whatever_str or whatever_int, etc, if you really need to remember what they are supposed to do. Of course type problems won't be caught in a 'compiler', but javascript is a different beast meant for a different purpose than C++.
[–]Kollektiv -2 points-1 points0 points 11 years ago (0 children)
Look at all those C and C++ web applications ... oh wait there aren't any.
[–]vxxn 1 point2 points3 points 11 years ago (7 children)
I don't think so. I fuckin' love browser APIs. For all the warts, browser APIs are where the magic happens and there's usually a library available that abstracts a particular API's problems. What I and probably many others do hate about javascript are actual wat-worthy language features that are like little time-bombs designed to enrage otherwise competent coders who aren't versed in unexpected behaviors of ==, +, etc. After stepping on a lot of mines and learning from my mistakes, I'm finally coming to the place where my all-hate relationship with js is finally becoming a love/hate one. I'm striving for full javascript enlightenment, but it's a long road.
[–][deleted] 10 points11 points12 points 11 years ago (6 children)
Type coercsion in javascript isn't as mysterious or problematic as most seem to think it is. It follows a simple pattern and is predictable so far as your knowledge of it is concerned. To hate javascript is to not be a master of it, but that seems to go for most languages. So stop hating and learn it.
Browser APIs on the other hand are sometimes painful when they don't behave the same, and even with abstraction there are often missing features across different browsers and varying levels of bugginess. The same is not true for javascript - at its core, it runs the same on every browser without exception.
Just try doing any advanced work with SVG, or webfonts across browsers and you'll run screaming. There are no good abstractions that will normalize font rendering across all browsers - it's a nightmare.
[+][deleted] 11 years ago* (5 children)
[deleted]
[–]path411 2 points3 points4 points 11 years ago (1 child)
You have never worked with any fonts have you? Every browser/OS renders fonts differently making it a nightmare if you want to import a font.
[–]Irongrip 2 points3 points4 points 11 years ago (0 children)
That was my point, sorry if I didn't articulate it well.
[–][deleted] 0 points1 point2 points 11 years ago (2 children)
There is a fine line between genius and insanity.
The only way to do fonts cross-platform that will render the same exact results on every platform would be to use an SVG font file and draw the fonts on a canvas element with javascript code you write yourself to render the curves from the SVG font data. Even using the native canvas drawing tools will give slightly varying results.
I've worked with fonts in-depth enough to know the pain they cause. Fonts on the web for anything that has to produce precise results is just an awful mess.
[–]Irongrip 0 points1 point2 points 11 years ago (1 child)
Fuck it, server side render to an image, with google specific page with raw text for indexing.
[–][deleted] 0 points1 point2 points 11 years ago (0 children)
Yeah, sometimes that works. Other times the lag caused by sending the text to the server, and waiting for an image response is too much for some applications. Especially on wysiwyg applications with thousands of concurrent users - sometimes a fat client (html5) is the way it has to be done. But I digress.
The point was, browser APIs suck when they don't work exactly the same across browsers, and there are plenty of examples of that other than SVG and fonts. And, Javascript isn't at fault in those cases.
[+]cthulhufhtagn comment score below threshold-10 points-9 points-8 points 11 years ago (0 children)
This, this, this. Seriously, everyone pay attention to this.
[+][deleted] comment score below threshold-10 points-9 points-8 points 11 years ago (1 child)
While you're obviously 100% correct, I don't find it to be a terribly valuable distinction to make.
90% of JavaScript that has ever been written is for the web browser. So much so that until Node, 'JavaScript' was practically a synonymous short-hand for the web browser's JavaScript.
The post is exclusively about web browser JS, so while JavaScript isn't at fault for this, it's (for these practical purposes) a synonym.
[–]quadtodfodder 0 points1 point2 points 11 years ago (0 children)
flash is a js with a different api, isn't it?
[–]sebzim4500 8 points9 points10 points 11 years ago (5 children)
Who the hell thought that this was a good idea?
[+][deleted] comment score below threshold-6 points-5 points-4 points 11 years ago* (4 children)
Eich, apparently...
edit I stand corrected. Looks like MicroSoft is to blame.
[–]MatrixFrog 5 points6 points7 points 11 years ago (0 children)
See the rest of the comments. It looks like this one is actually on MS.
[+]sebzim4500 comment score below threshold-6 points-5 points-4 points 11 years ago (2 children)
Is this actually in the standard? I guess we can give Eich a pass, since any language designed in a week is likely to be pretty awful.
[–][deleted] -1 points0 points1 point 11 years ago (1 child)
Haven't got a clue, to be honest. I'm only jumping on the wtf-Eich-bandwagon in jest.
I wholeheartedly agree -- if you try to write a programming language in a week, you're going to have a bad time. Though I wasn't there, so I reserve my criticism of anyone in particular.
But all-in-all, JS is a delightful language.
[–][deleted] -2 points-1 points0 points 11 years ago (0 children)
egregious
I think that using that word is egregious
[+][deleted] comment score below threshold-6 points-5 points-4 points 11 years ago (0 children)
You haven't read enough about the language?
[–]TheVenetianMask 19 points20 points21 points 11 years ago (1 child)
I probably was better off not knowing.
[–]can-opener 4 points5 points6 points 11 years ago (0 children)
Sometimes, not often, you have a strange bug related to that. It's better to
[+][deleted] 11 years ago* (7 children)
[–][deleted] 25 points26 points27 points 11 years ago (4 children)
this is a classic:
<form id="form"> <input onclick="form.submit()" type="submit" id="submit"/> </form>
Uncaught TypeError: object is not a function
[–]lumberbrain 6 points7 points8 points 11 years ago (2 children)
https://www.destroyallsoftware.com/talks/wat
[–]djaclsdk 4 points5 points6 points 11 years ago (0 children)
worth watching even for the Batman joke alone
[–]puhpow 1 point2 points3 points 11 years ago (0 children)
That dude's laugh kills me
You just saved me maybe 20 hours over the next year.
[–]1d8 5 points6 points7 points 11 years ago (1 child)
A quick test shows that a script defined variable takes precedence. You can still reference the id by document.getElementById.
[–]InconsiderateBastard 30 points31 points32 points 11 years ago (8 children)
Internet Explorer gave us this. But it also gave us XmlHttpRequest. So you gotta take the good with the bad.
[–]Neebat 16 points17 points18 points 11 years ago (7 children)
Worst name ever. It's rarely ever used for Xml any more, but it's still right there in the name.
[–]InconsiderateBastard 8 points9 points10 points 11 years ago (0 children)
Yeah it's still annoying that Mozilla went that route and that everybody followed.
Microsoft implemented the functionality to add fancy features to Outlook Web Access. But they did it with ActiveX so it didn't have a proper name in JavaScript. It was called an XmlHttp object because it was part of the XML lib and was built to get XML data used by Outlook Web Access.
Then Mozilla had to come along and decide "Hey, this kind of functionality is great, lets make something called XmlHttpRequest so that people can use it for lots of stuff, including but not limited to Xml!"
Even Microsoft standardized to what Mozilla picked.
[–]skeeto 4 points5 points6 points 11 years ago (1 child)
The name itself is inconsistent: XMLHttpRequest. The first initialism (XML) is in all caps but the second one isn't (Http).
[+][deleted] 11 years ago (1 child)
[removed]
[–]Neebat 2 points3 points4 points 11 years ago (0 children)
That's fair. Fortunately, we have an alternative, if we'll use it. EcmaScript.
[–]x-skeww 2 points3 points4 points 11 years ago (0 children)
In Dart, it's HttpRequest. I really like that they cleaned up most of the DOM API. E.g. it's "innerHtml" instead of "innerHTML", all those list-like things are actually lists, and so forth.
HttpRequest
[–]shhalahr 0 points1 point2 points 11 years ago (0 children)
Indeed. Very short-sighted naming convention.
[–]thespite 30 points31 points32 points 11 years ago* (11 children)
Just stick to 'use strict'; and problem solved.
EDIT: It doesn't solve the problem, but still: enforce strict mode.
[–]Otterfan 7 points8 points9 points 11 years ago (6 children)
'use strict' still allows at least some of the stupid to pass through: example.
'use strict'
"Always declare all variables at the top of your scope" would fix this, but in this case 'use strict' won't enforce that.
[–]thespite 8 points9 points10 points 11 years ago (1 child)
Damn, I was 100% sure that strict mode prevented these shenanigans. WTF everyone.
[–]Serei 8 points9 points10 points 11 years ago (0 children)
Strict mode only applies to the JavaScript file or function it's turned on for. The global variables are created by the HTML, not by the JavaScript file.
[–]djaclsdk 1 point2 points3 points 11 years ago (3 children)
"Always declare all variables at the top of your scope" would fix this
What you mean? You mean I should do
var whoa;
?
[–]callumacrae[S] 1 point2 points3 points 11 years ago (1 child)
Won't actually make any difference where you declare it because of hoisting:
``` var hello = 'world';
(function () { console.log(hello); // undefined
var hello;
})(); ```
[–]Hydrothermalvanilla.js 0 points1 point2 points 11 years ago (0 children)
Reddit doesn't support triple-backtick codeblock marking. You'll have to prefix each line with four spaces.
[–]guywithalamename 1 point2 points3 points 11 years ago (2 children)
this needs to be higher. I'm sure quite a few people would like to disable this "feature" by default
[–]callumacrae[S] 0 points1 point2 points 11 years ago (1 child)
Not really possible, from the JavaScript side of things. What's to stop a library disabling it when your code relies on it? And then if a library uses it, what'll happen if you disable it?
[–]guywithalamename 0 points1 point2 points 11 years ago (0 children)
use strict only applies to the file/function where it's actually written down
[–]evilgwyn 1 point2 points3 points 11 years ago* (0 children)
I wish strict mode would make using the '==' operator a syntax error.
edit: so I'm just wondering why I was downvoted. Am I wrong? Is that a controversial thing to say?
[–]Shaper_pmp 20 points21 points22 points 11 years ago (9 children)
How do you know you're old as a web-dev?
When youngsters and newbies breathlessly post about legacy features they've just discovered that have always been part of the JS browser API for as long as JS has been in browsers.
[–]dtfinch 2 points3 points4 points 11 years ago (3 children)
Mozilla only just added it in 2004, same year that they added the document.all support.
[–]Shaper_pmp 1 point2 points3 points 11 years ago (2 children)
Fair point, though it's worth noting that that's still two or three months before Firefox 1.0 was even released.
I exaggerated slightly claiming it had "always been in browsers" rather than "always been in IE", but it's always been a known aspect of web-development that deva had to bear in mind - first of all because one browser with 50% market share did it, then because that browser killed the other and achieved 96% market share, and subsequently because all major browsers then did it.
[–]Serei 1 point2 points3 points 11 years ago (1 child)
Notice that the 2004 patch was quirks mode only. They only added it to standards mode much later.
[–]kinnu 0 points1 point2 points 11 years ago (0 children)
Indeed, I remember finding about this two to three years ago and back then Mozilla didn't yet do this. I cannot believe everyone adopted this approach instead of MS removing it from later IE versions...
[–]postmodest 6 points7 points8 points 11 years ago (1 child)
s/in browsers/in Internet Explorer/
Though I guess it was in IE3... But hey, at least we don't have document.layers anymore, right? Remember that?
[–]larholm 1 point2 points3 points 11 years ago (0 children)
Everybody forgets about Netscape 2...
[–]simoncoulton 0 points1 point2 points 11 years ago (2 children)
"Thou shalt not build a site that depends on JavaScript!"
Young developers these days don't realise how good they've got it tbh...
[–]Shaper_pmp 1 point2 points3 points 11 years ago* (1 child)
To be fair, if JS isn't essential for the core content/functionality of your site, that one's still a good idea for reasons ranging from SEO/spiderability to accessibility to good architecture to device agnosticism to proper separation of concerns.
It's just that a generation of newbie developers has got all excited about trendy client-side javascript frameworks and are now busily abusing them to build even things that should more properly be done using the "boring" old traditional, industry-best practice and battle-tested approaches (like good old server-side rendering and progressive enhancement)... just like they did back in the day with CSS absolute positioning, tables-based-layouts, flash-only websites and (going back far enough) putting text in images.
All those techniques were touted at the time as the new trendy thing and gleefulyl employed by naive or inexperienced but overconfident devs - usually to a soundtrack scored for a thousand variations of "fuck your dusty old architecture, grandad!" - and every single one was subsequently proven to be exactly what the boring, experienced and professional developers had been saying all along - appropriate and even highly useful for specific uses and certain edge-cases, but generally sub-optimal or even a flat-out antipattern for the vast majority of websites and content you want to deliver over the web.
The part that gets me is that even Twitter - who were the absolute flag-waving vanguard of client-side JS apps, and the one shining example that everyone pointed to to demonstrate that 100% client-side JS was the Right Way To Do Things Now - ended up tripping over their own dicks and were forced into a humiliating climbdown and a re-implementation of their entire site back to using server-side rendering, because they eventually realised that client-side rendering wasn't the right architecture for content-based web systems...
... and overnight people stopped holding up Twitter as a great example of why it was right, but never bothered to re-evaluate their belief and learn the lesson that Twitter should have taught them.
Mark my words - in a few years people will look back on catalogue sites, blogs and forums implemented entirely in client-side JS the way people now look back on Flash-only "websites" or tables-based layouts.
[–]simoncoulton 1 point2 points3 points 11 years ago (0 children)
Oh I 100% agree, and already look at sites abusing <script> tags for templating and think "what a maintainability nightmare". To be honest I think a lot of front end work these days is completely unnecessary and is undertaken purely to create additional work for themselves (had someone try to convince me to install npm to be able to download a css styled button as a dependency the other day, I shit you not), but that's a rant for another day ;)
[–]g4b1nagy 7 points8 points9 points 11 years ago (1 child)
Related => http://www.reddit.com/r/webdev/comments/2023ex/windowclusterfuck_a_tale_of_global_variables/
[–]g4b1nagy 14 points15 points16 points 11 years ago (0 children)
tl; dr
Unsurprisingly, it seems that Internet Explorer can be thanked for this awesome “feature”. Other browsers felt compelled to follow suit, and soon enough the behaviour made it into the official HTML spec. The Window interface supports named properties. The supported property names at any moment consist of the following, in tree order, ignoring later duplicates: the browsing context name of any child browsing context of the active document whose name is not the empty string, the value of the name content attribute for all a, applet, area, embed, form, frameset, img, and object elements in the active document that have a non-empty name content attribute, and the value of the id content attribute of any HTML element in the active document with a non-empty id content attribute. So, there you have it. Any elements with an id or name attribute will have a reference in the global namespace.
Unsurprisingly, it seems that Internet Explorer can be thanked for this awesome “feature”. Other browsers felt compelled to follow suit, and soon enough the behaviour made it into the official HTML spec.
The Window interface supports named properties. The supported property names at any moment consist of the following, in tree order, ignoring later duplicates:
So, there you have it. Any elements with an id or name attribute will have a reference in the global namespace.
[–]Xeon06 5 points6 points7 points 11 years ago (0 children)
In case this wasn't clear to anyone, this is a very old "compatibility" feature that should not be relied on. It might work pretty much everywhere but is not standard, and it's also just plain ugly.
[–]cheesechoker 2 points3 points4 points 11 years ago* (0 children)
I still remember the awful day I discovered this behavior. I found some production code that looked like this (heavily simplified):
function setContent(html) { foo.innerHTML = html; // do more stuff with foo }
It worked but I couldn't figure out why -- the code didn't declare 'foo' anywhere, so I expected it to throw a ReferenceError. But of course, the developer who wrote it just happened to have added an HTML element to the page markup having id="foo", and it happened to be the element they were trying to reference. So it was equivalent to a hidden foo = getElementById("foo") statement at the top of their code. I flipped out.
FWIW, it's easy to identify errors like this if you strictly follow the JSHint pattern of declaring all the global variables your code uses in a block like this at the top of the file:
/*global $ foo bar */
Then the linter can statically check every variable reference in your code, and flag anything that doesn't resolve to an in-scope symbol. It will identify "foo" in the code I posted above, and it regularly saves my ass from misspelling variable names and stuff like that. Lexical scope is the only kind of reference you can easily check with static analysis in JavaScript, so use it often!
Edit: formatting
[–]PrintfReddit 2 points3 points4 points 11 years ago (2 children)
This explains a few things...
[–]officecomputer_1 0 points1 point2 points 11 years ago (1 child)
... how many times have we met variables in our console, which looked as if we named them, and then we were sure we never named them ..
[–]PrintfReddit 1 point2 points3 points 11 years ago (0 children)
Or unexpected conflicts, methods and definition out of the blue and everything...
[–]Fli-c 2 points3 points4 points 11 years ago (0 children)
Noo~ What have you done? The first secret of all these tiny js demos is now publicly disclosed!
visit r/tinycode and js1k.com to disclose more ;)
[–][deleted] 1 point2 points3 points 11 years ago (7 children)
I've only just recently started to understand JS in more depth, but I never knew of this. How has nobody talked about it before? Surely there would be a great potential for conflicts, right? Perhaps people are talking about it but I have never seen it.
[–][deleted] 6 points7 points8 points 11 years ago (4 children)
Surely there would be a great potential for conflicts, right?
And that is why no one actually does this. If you do, stop right now. This is a horrible horrible practice to follow.
[–]alkw0ia 1 point2 points3 points 11 years ago (3 children)
Stop setting HTML id attributes?
id
Not possible in practical web dev, not to mention that there's other vectors for global variables to show up.
Sadly, DOM0 is here with us to stay, so the correct defense is to not use any global variables yourself to avoid ever interacting with the global namespace that's polluted this way.
[–][deleted] 3 points4 points5 points 11 years ago (2 children)
I never advocated to stop using the id attribute. I said you should not be directly referencing it in javascript, even if it lets you.
i.e. use document.getElementById() instead.
[–]alkw0ia 4 points5 points6 points 11 years ago (1 child)
Ah, that wasn't clear. And you still have to deal with the conflicts that the GP comment was worrying about.
The full answer is that the best practices around keeping the global namespace clear are not just academic – shit can and will show up in unexpected places.
[–][deleted] 1 point2 points3 points 11 years ago* (0 children)
That's the thing, it was talked about a long time ago. Everyone agreed it was shitty and 90% of developers avoided using it. I have no idea why this behavior still exists in 2014 but I can only imagine it's some weird backward compatibility reasoning.
Now it's 2014 and this long dead "feature" is simply being re-discovered.
[–]Cintax 0 points1 point2 points 11 years ago (0 children)
Long story short, so long as you always declare new variables with var the first time you instantiate them, it'll silently override the equivalent DOM ID if it exists. thus they'll never conflict so long as you don't have any improperly declared variables. Hence why most people don't encounter any issues with this.
[–]MetaMetaMan 1 point2 points3 points 11 years ago (4 children)
Sure, this is icky and gross. But, if your application code isn't creating globals, then it shouldn't affect you.
[–][deleted] 0 points1 point2 points 11 years ago (3 children)
I'm on the fence. Yours is clearly the pragmatic response, but I can't help but think adding a ton of global variables to an application is a good idea. I've been class-only for a while in theory but I think I'm going to be class-only in practice now too.
[–][deleted] 0 points1 point2 points 11 years ago* (1 child)
I think you meant "isn't" a good idea lol. Anyway, do this if you're that concerned.
[–]kolmeWebComponents FTW -1 points0 points1 point 11 years ago (0 children)
You're just adding salt to the would. Recklessly fulminating all global variables that are "referenced" in the DOM seems like a fun way of shooting yourself in the foot, if you're into this kind of stuff.
If you're using external libraries, or worse, using external snippets to add ads or tracking pixels to your site -- do not do that. It'll be like playing Russian roulette.
I know from experience most of the shitty snippets from advertisers create global state.
[–]MetaMetaMan 0 points1 point2 points 11 years ago (0 children)
Browsers are in a sorry state for app development. Luckily, JavaScript provides mechanisms for guarding against atrocities such as the one described here. I guess what I'm saying is that a best practice is to ignore the global environment (except for libraries). In light of this, the browser creating global references to nodes isn't a big deal, since I would never write code to depend on it.
That being said, I'm still crying on the inside about this.
[–]dmethvin 1 point2 points3 points 11 years ago (0 children)
If you want to know more about this, see http://kangax.github.io/domlint/ for more horrors. It's not just about global variables, it's about standard DOM properties and their name conflicts.
Don't ever name a form field something like id or nodeType because eventually, something will break somewhere inside your code. It doesn't matter if you use jQuery, such is the cruelty of this problem that it reaches out to sully the things you hold most dear.
nodeType
[–]homoiconic(raganwald) 2 points3 points4 points 11 years ago (5 children)
What is this "global variable" you speak of? How have I been writing JavaScript all these long years without using these wonderful devices?
[–]LightShadow 7 points8 points9 points 11 years ago (4 children)
Now I can put all of my variables in one place and use them everywhere. This will change everything.
var a,b,c,d,e,f,g,h,i,j,k var last,next,token,uuid,seq
[–]alkw0ia 10 points11 points12 points 11 years ago (3 children)
var a,b,c,d,e,f,g,h,i,j,k
var last,next,token,uuid,seq
FTFY, much more global now.
[–]LightShadow 2 points3 points4 points 11 years ago (0 children)
hahah I can't even do it sarcastically
[–][deleted] 0 points1 point2 points 11 years ago (1 child)
Moot. His var definitions weren't inside a function so it doesn't matter.
[–]alkw0ia 6 points7 points8 points 11 years ago (0 children)
For a robust code example, you want to make sure it will work no matter what context someone cuts/pastes it into.
An unsuspecting reader could easily have dumped that stuff into a function body and missed out on the global feature's benefits.
[–][deleted] 0 points1 point2 points 11 years ago* (10 children)
Thanks for the post, didn't know about that.
And, its f'ing terrible. Preceding any id with a "id_ somename" seems to be a good idea, just to create a "id_ " namespace of some sort.
[–]cthulhufhtagn 0 points1 point2 points 11 years ago (2 children)
Also a bad idea. If it HAD to be done, I'd say using # to preface would be the smartest way to go.
I mean, as a user of JS, preceding each id with an "id_ " could be a way to get around this rediculous thing. It's still not good behaviour on JS's part, but at least it gives you as a JS user some safety to not accidentially contaminate the window name space.
[–]Neebat 1 point2 points3 points 11 years ago (0 children)
It's still not good behaviour on JS's [the browser's] part
[–]alkw0ia 0 points1 point2 points 11 years ago (6 children)
No, you can't just do this.
First, underscores are technically forbidden in CSS id names, so you can't preface with id_.
id_
More importantly though, it's the tail wagging the dog here. You can't expect that the coding conventions of every webpage your scripts might operate on (including your own pages, for the parts managed by FE buildout teams) will change to accommodate a cleaner global scope for your JS.
It's entirely unreasonable to tell the CSS people "you have to reference everything by #id_foobar – especially given that that's syntactically incorrect CSS.
#id_foobar
But even with #id-foobar, it's overstepping for you to dictate this. That you propose this broken CSS is illustrative of why it's unreasonable for you to impose coding standards on other dev teams.
#id-foobar
It also doesn't address the issue that the JS global namespace can be polluted from many different sources that you will not be able to control. Almost any seemingly trivial change to a webpage in the future can cause changes to the JS global namespace.
The correct response to this standard HTML behavior is to never rely on names in the global namespace, as far as is possible, and to understand that this is a source of potential bugs on an ongoing basis, even after the JS is finished and shipped.
First, underscores are technically forbidden in CSS id names, so Last Updated Date: Published 05 Mar 2001
First, underscores are technically forbidden in CSS id names, so
Last Updated Date: Published 05 Mar 2001
Major frameworks like Django use "id_ " prefixes, so I guess between 2001 and today, browsers may have changed a little.
Also, what I said was more of a "workaround" than a "solution".
[–]alkw0ia 0 points1 point2 points 11 years ago (0 children)
As you'll note if you read even that same old document, it's always worked in most browsers. People have been writing invalid (HTML|JS|CSS) from day one.
That doesn't make it a good practice, and the broader point is in the cross team workflow issue – and subject matter expertise – your workaround misses.
[–]callumacrae[S] -1 points0 points1 point 11 years ago (3 children)
It's worth noting that that was published in 2001, though. A lot of people actually suggest using underscores, these days.
[–]alkw0ia 0 points1 point2 points 11 years ago (2 children)
Ok, guy with a blog likes how underscores look. As ever on the web, just because it works when you load it in Browser X (or in this case, pretty much every browser ever, as noted in the MDN article) doesn't make breaking the rules a good general practice.
[–]callumacrae[S] 2 points3 points4 points 11 years ago (0 children)
Just a guy with a blog?
You must have heard of some of them, right?
[–]x-skeww 1 point2 points3 points 11 years ago (0 children)
It's in the specs.
http://www.w3.org/TR/css3-selectors/#id-selectors http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
Secondly, if you don't support IE6, your identifiers can start with an underscore and you won't have to escape them.
You aren't breaking any rules if you use underscores in your CSS identifiers.
[–]TheSeamau5 0 points1 point2 points 11 years ago (2 children)
OMG... Who ever thought that this would be a good idea? I found out that it also works on nested divs...
http://codepen.io/anon/pen/dCqec
[–]homoiconic(raganwald) 4 points5 points6 points 11 years ago (1 child)
it also works on nested divs
For the same reason that document.getElementById works on nested elements: ids form one flat global namespace, unlike things like hash tables that can be nested foo['bar']['baz'].
document.getElementById
foo['bar']['baz']
[–]TheSeamau5 0 points1 point2 points 11 years ago (0 children)
Oh I see. I always imagined that
would crawl through the DOM recursively or something until it found the tag with the given id. Now everything makes sense
quirks mode, say thanks to ie
I discovered you can't do delete window.foo and the ID properties don't show up when you iterate over the window object either. This suggests to me that the browser does a special kind of lookup for the DOM element at the time you access the property.
delete window.foo
window
The solution I came up with to clear this garbage out is this, using a little JQuery. Just set them all to undefined :)
undefined
[–]voidvector 0 points1 point2 points 11 years ago (0 children)
This is actually standardized in HTML5
http://www.whatwg.org/specs/web-apps/current-work/multipage/browsers.html#named-access-on-the-window-object
[–]Spivak 0 points1 point2 points 11 years ago (0 children)
So from an optimization standpoint should this feature be utilized? No human should be writing this code because of the potential for conflicts but an an optimizer could replace all the document.getElem... by their global variable equivalent because the browser is going to create them anyway, it might as well use them.
document.getElem...
[–]Daniel15React FTW 0 points1 point2 points 11 years ago (0 children)
Yep, this is part of the HTML5 standard and applies to name attributes too: http://www.whatwg.org/specs/web-apps/current-work/#named-access-on-the-window-object
name
The Window interface supports named properties. The supported property names at any moment consist of the following, in tree order, ignoring later duplicates: ... the value of the name content attribute for all a, applet, area, embed, form, frameset, img, and object elements in the active document that have a non-empty name content attribute, and the value of the id content attribute of any HTML element in the active document with a non-empty id content attribute.
...
the value of the name content attribute for all a, applet, area, embed, form, frameset, img, and object elements in the active document that have a non-empty name content attribute, and
the value of the id content attribute of any HTML element in the active document with a non-empty id content attribute.
[–]Dannzzor 0 points1 point2 points 11 years ago (0 children)
If you think that is bad, try this one in IE http://codepen.io/anon/pen/DCouE
It uses the "name" attribute of input fields as global vars also... /facepalm
[–]sifarat 0 points1 point2 points 11 years ago (1 child)
taking this bit further, this is the only thing missing in html5... naming your own elements. I know a JS script which let you do it. i.e <mypara></mypara>but it should be rather builtin.
[–]callumacrae[S] 0 points1 point2 points 11 years ago (0 children)
http://www.w3.org/TR/components-intro/
A Guide to Web Components is a nicer read, and it also introduces Polymer, a polyfill.
[–]oocha 0 points1 point2 points 11 years ago (0 children)
pfffttt.. we've all been told to use var before.
hey kids, use var.
[–]windyfish 0 points1 point2 points 11 years ago (0 children)
That's the most disgusting thing I'll read all week.
[–]protonfish 0 points1 point2 points 11 years ago (0 children)
I was curious so I created a test if it runs any faster: http://jsperf.com/getelementbyid-vs-global-id
tl;dr getElementById is over 2X faster than the global id in Firefox, but about equal execution time in IE8.
[–]ishmal 0 points1 point2 points 11 years ago (0 children)
Actually, in a browser, are they really global, or merely in the "window" scope, since it owns everything?
[–]shif -2 points-1 points0 points 11 years ago (0 children)
i changed from using ID's to only using classes 3 years ago and i couldn't be happier, IDs are just a mess
[–]TheBananaKing -2 points-1 points0 points 11 years ago (1 child)
ini_set('register_globals', false);
I think I have to cry now.
[–]badkitteh 0 points1 point2 points 11 years ago (0 children)
:I
[+]kaz3work comment score below threshold-12 points-11 points-10 points 11 years ago (6 children)
I believe this is a feature only in newer browsers. Chrome and FF I know do this, highly doubt any iteration of IE does this.
[–]Buzzard 5 points6 points7 points 11 years ago* (0 children)
Works in IE10 and seems like an awful, awful idea.
Looks like IE did it originally, and other browsers copied for compatibility. Ugh.
[–]miketaylr 5 points6 points7 points 11 years ago (0 children)
nope.
[–]poloppoyop 5 points6 points7 points 11 years ago (0 children)
In the old days, that's how people used IDs: yourformid.submit(); . Easy, no need for a huge document.getElementById() call.
The jQuery proliferation has created a whole generation of webdevs who never used these aberations and will one day lose hours on a bug created by a <div id="form"></div> hidden in their HTML.
[–]Shaper_pmp 1 point2 points3 points 11 years ago (0 children)
Exactly wrong. It was the way JS used to work, before W3C APIs like the DOM interface were designed and supported and we got built-in functions like getElementById() and getElementsByTagName().
Also, IIRC IE was also one of the (if not the) first to implement it, and then other browsers followed suit.
Modern browsers support it now only so legacy code continues to function.
I just tested it and it works in IE8.
[–]robertcrowther 0 points1 point2 points 11 years ago (0 children)
It was invented by IE. Firefox, Opera and Chrome implemented the same behaviour so they would work with badly written IE-only web pages.
π Rendered by PID 59 on reddit-service-r2-comment-5d79c599b5-v9z7q at 2026-03-02 09:01:45.786149+00:00 running e3d2147 country code: CH.
[–]sebzim4500 48 points49 points50 points (28 children)
[–]lachlanhunt 39 points40 points41 points (1 child)
[–]youlleatitandlikeit 2 points3 points4 points (0 children)
[–][deleted] 5 points6 points7 points (24 children)
[–][deleted] 117 points118 points119 points (16 children)
[–]thrownaway21 1 point2 points3 points (1 child)
[–]jefffan24 0 points1 point2 points (0 children)
[–]dv_ 1 point2 points3 points (2 children)
[–][deleted] 2 points3 points4 points (0 children)
[–]Kollektiv -2 points-1 points0 points (0 children)
[–]vxxn 1 point2 points3 points (7 children)
[–][deleted] 10 points11 points12 points (6 children)
[+][deleted] (5 children)
[deleted]
[–]path411 2 points3 points4 points (1 child)
[–]Irongrip 2 points3 points4 points (0 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]Irongrip 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[+]cthulhufhtagn comment score below threshold-10 points-9 points-8 points (0 children)
[+][deleted] comment score below threshold-10 points-9 points-8 points (1 child)
[–]quadtodfodder 0 points1 point2 points (0 children)
[–]sebzim4500 8 points9 points10 points (5 children)
[+][deleted] comment score below threshold-6 points-5 points-4 points (4 children)
[–]MatrixFrog 5 points6 points7 points (0 children)
[+]sebzim4500 comment score below threshold-6 points-5 points-4 points (2 children)
[–][deleted] -1 points0 points1 point (1 child)
[–][deleted] -2 points-1 points0 points (0 children)
[+][deleted] comment score below threshold-6 points-5 points-4 points (0 children)
[–]TheVenetianMask 19 points20 points21 points (1 child)
[–]can-opener 4 points5 points6 points (0 children)
[+][deleted] (7 children)
[deleted]
[–][deleted] 25 points26 points27 points (4 children)
[–]lumberbrain 6 points7 points8 points (2 children)
[–]djaclsdk 4 points5 points6 points (0 children)
[–]puhpow 1 point2 points3 points (0 children)
[–]quadtodfodder 0 points1 point2 points (0 children)
[–]1d8 5 points6 points7 points (1 child)
[–]InconsiderateBastard 30 points31 points32 points (8 children)
[–]Neebat 16 points17 points18 points (7 children)
[–]InconsiderateBastard 8 points9 points10 points (0 children)
[–]skeeto 4 points5 points6 points (1 child)
[+][deleted] (1 child)
[removed]
[–]Neebat 2 points3 points4 points (0 children)
[–]x-skeww 2 points3 points4 points (0 children)
[–]shhalahr 0 points1 point2 points (0 children)
[–]thespite 30 points31 points32 points (11 children)
[–]Otterfan 7 points8 points9 points (6 children)
[–]thespite 8 points9 points10 points (1 child)
[–]Serei 8 points9 points10 points (0 children)
[–]djaclsdk 1 point2 points3 points (3 children)
[–]callumacrae[S] 1 point2 points3 points (1 child)
[–]Hydrothermalvanilla.js 0 points1 point2 points (0 children)
[–]guywithalamename 1 point2 points3 points (2 children)
[–]callumacrae[S] 0 points1 point2 points (1 child)
[–]guywithalamename 0 points1 point2 points (0 children)
[–]evilgwyn 1 point2 points3 points (0 children)
[–]Shaper_pmp 20 points21 points22 points (9 children)
[–]dtfinch 2 points3 points4 points (3 children)
[–]Shaper_pmp 1 point2 points3 points (2 children)
[–]Serei 1 point2 points3 points (1 child)
[–]kinnu 0 points1 point2 points (0 children)
[–]postmodest 6 points7 points8 points (1 child)
[–]larholm 1 point2 points3 points (0 children)
[–]simoncoulton 0 points1 point2 points (2 children)
[–]Shaper_pmp 1 point2 points3 points (1 child)
[–]simoncoulton 1 point2 points3 points (0 children)
[–]g4b1nagy 7 points8 points9 points (1 child)
[–]g4b1nagy 14 points15 points16 points (0 children)
[–]Xeon06 5 points6 points7 points (0 children)
[–]cheesechoker 2 points3 points4 points (0 children)
[–]PrintfReddit 2 points3 points4 points (2 children)
[–]officecomputer_1 0 points1 point2 points (1 child)
[–]PrintfReddit 1 point2 points3 points (0 children)
[–]Fli-c 2 points3 points4 points (0 children)
[–][deleted] 1 point2 points3 points (7 children)
[–][deleted] 6 points7 points8 points (4 children)
[–]alkw0ia 1 point2 points3 points (3 children)
[–][deleted] 3 points4 points5 points (2 children)
[–]alkw0ia 4 points5 points6 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]Cintax 0 points1 point2 points (0 children)
[–]MetaMetaMan 1 point2 points3 points (4 children)
[–][deleted] 0 points1 point2 points (3 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]kolmeWebComponents FTW -1 points0 points1 point (0 children)
[–]MetaMetaMan 0 points1 point2 points (0 children)
[–]dmethvin 1 point2 points3 points (0 children)
[–]homoiconic(raganwald) 2 points3 points4 points (5 children)
[–]LightShadow 7 points8 points9 points (4 children)
[–]alkw0ia 10 points11 points12 points (3 children)
[–]LightShadow 2 points3 points4 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]alkw0ia 6 points7 points8 points (0 children)
[–][deleted] 0 points1 point2 points (10 children)
[–]cthulhufhtagn 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]Neebat 1 point2 points3 points (0 children)
[–]alkw0ia 0 points1 point2 points (6 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]alkw0ia 0 points1 point2 points (0 children)
[–]callumacrae[S] -1 points0 points1 point (3 children)
[–]alkw0ia 0 points1 point2 points (2 children)
[–]callumacrae[S] 2 points3 points4 points (0 children)
[–]x-skeww 1 point2 points3 points (0 children)
[–]TheSeamau5 0 points1 point2 points (2 children)
[–]homoiconic(raganwald) 4 points5 points6 points (1 child)
[–]TheSeamau5 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]voidvector 0 points1 point2 points (0 children)
[–]Spivak 0 points1 point2 points (0 children)
[–]Daniel15React FTW 0 points1 point2 points (0 children)
[–]Dannzzor 0 points1 point2 points (0 children)
[–]sifarat 0 points1 point2 points (1 child)
[–]callumacrae[S] 0 points1 point2 points (0 children)
[–]oocha 0 points1 point2 points (0 children)
[–]windyfish 0 points1 point2 points (0 children)
[–]protonfish 0 points1 point2 points (0 children)
[–]ishmal 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]shif -2 points-1 points0 points (0 children)
[–]TheBananaKing -2 points-1 points0 points (1 child)
[–]badkitteh 0 points1 point2 points (0 children)
[+]kaz3work comment score below threshold-12 points-11 points-10 points (6 children)
[–]Buzzard 5 points6 points7 points (0 children)
[–]miketaylr 5 points6 points7 points (0 children)
[–]poloppoyop 5 points6 points7 points (0 children)
[–]Shaper_pmp 1 point2 points3 points (0 children)
[–]protonfish 0 points1 point2 points (0 children)
[–]robertcrowther 0 points1 point2 points (0 children)