Scope in Javascript

November 23, 2010  |  Development

We all have those “oh…that makes sense” moments in software development.  Just after you learn something new when you feel that you must’ve only had half a brain the day before because you just couldn’t grasp a concept.   Well I’ve been hoping for that day to come with one particular frustration: scoping in Javascript.  And it finally has.

After reading which linked to the more concise reference, the moment of clarity came.

Apparently, my frustrations with scope in Javascript was simply a misunderstanding of the var keyword.  Before this revelation, I didn’t really think the var keyword was that important.  I thought it was a way for programmers to say, “This is a new variable that I’m creating.  Not a reference to a pre-existing one”.   Oops.

  • Skilldrick

    That’s right. The real issue is that of implicit global variables – that is, if you don’t use var you’re implicitly saying “I’d like to use/create a global variable”, which is a really bad idea. But we’re stuck with it! Luckily there’s jslint to stop us from making mistakes like that.