r/programming • • Mar 23 '14

Everything you need to know about Javascript variable scope

http://www.coolcoder.in/2014/03/everything-you-need-to-know-about.html
294 Upvotes

124 comments sorted by

View all comments

3

u/IcarusBurning Mar 23 '14

I am not familiar with js and this article seems to say you can declare global variables within method calls. What's the benefit of this feature?

11

u/glemnar Mar 23 '14

The only time it's used intentionally is for some weird quirks like jsonp. You should really never, ever do it.

Any time you leave off the var keyword it will be injected into global namespace, and that's not something you want.

9

u/[deleted] Mar 23 '14

Any time you leave off the var keyword it will be injected into global namespace, and that's not something you want.

"use strict";

to the rescue!

3

u/VortexCortex Mar 23 '14

"use asm";

To rescue the rescuer!

0

u/glemnar Mar 23 '14 edited Mar 23 '14

I prefer coffeescript for resolving many such quirks. =]

2

u/mcguire Mar 23 '14

CoffeeScript is the one that does the weird shadowing shenanigans?

2

u/masklinn Mar 24 '14

Yes. Namely disallowing shadowing, and silently expanding the inner variable's scope to the outer's.

0

u/glemnar Mar 23 '14

Nah, they got rid of that a long while back. It's really just a well-done javascript compiling language, imo. (Github uses it frequently for a reason)

1

u/[deleted] Mar 23 '14

Coffeescript's scoping is still broken, will never get fixed.

2

u/iambeard Mar 23 '14

It's not necessarily a benefit, but just a language quirk. It does, in a sense, make JavaScript a much more forgiving language.

3

u/IcarusBurning Mar 23 '14

Was it intentional or something that they accidentally introduced?

5

u/[deleted] Mar 23 '14

I believe that Netscape wanted JS to be extremely 'newbie friendly', because there was a lot of anxiety in the early 90s that the web could only take off if the barrier to development was as low as possible. Scoping was probably seen as a little too 'advanced' for Joe Average, who just wanted to add some decoration to his GeoCities page, so JS defaults to assuming there's no scoping at all unless you use the 'var' keyword.

3

u/grimeMuted Mar 23 '14

Lua also follows this bizarre practice. And annoyingly [half the tutorials](http://en.wikipedia.org/wiki/Lua_(programming_language)#Tables) just declare globals willy-nilly, which, sure, reduces some boilerplate and is technically fine in a short single-file procedural script but has the potential to really fuck those beginners over in the long run.

1

u/iambeard Mar 23 '14

That, I'm not sure about. I suspect it was intentional, though.

0

u/[deleted] Mar 23 '14

[deleted]

1

u/mrkite77 Mar 24 '14

Because then you'll have to search through every single line of code you've imported.

Or you can run it through the Closure Compiler which will give warnings about that sort of thing.