Does Javascript have block level scope?
Before we even discuss whether Javascript has block level scope, we should give a definition of what block scope really means.
What is block scope?
A programming language has block scope if a variable declared inside some block of code enclosed by curly braces is only visible within that block of code, and that variable is not visible outside of that particular block of code.
Think of a “block” of code as an an if statement, for loop, while loop, etc.
And, if a variable declared within a block of code is still visible outside of that block, then the programming language does not have block scope. Note that we deliberately did not mention functions as “blocks” of code – more on the topic of functions and scope later.
A test to see if Javascript has block scope
So, back to the original question: does Javascript have block scope?
Instead of just giving you a simple yes/no answer, let’s run a test to see if it does since that will really help you remember the answer:
function scopeTest() { /* consider this simple for loop to be the "block" that we were talking about earlier */ for (var i = 0; i <= 5; i++) { var inFor = i; } alert(inFor); // what happens here? } // call the function defined above scopeTest( );
In the code above, we have a variable called inFor that was declared in a for loop. We then try to access the inFor variable outside the for loop in the alert statement.
If the code above does not alert anything then we know it's because Javascript uses block scope. In a block scoped language, the variable inFor will not be visible outside of the for loop. This means that if Javascript is a block scoped language, then the call to "alert(inFor);" will not recognize the inFor variable, and nothing will be output to an alert box.
But, the code above actually outputs a "5", which means that the inFor variable does exist outside of the for loop, which must mean that Javascript does NOT have block scope. And there is our answer - Javascript does not have block scope.
Block scope vs Function scope
So, if Javascript doesn't use block scope, then what kind of scope does it use?
Well, Javascript uses something called function scope. You can read more about function scope in our article here: Function Scope in Javascript.
Basically, the difference between function scope and block scope is that in a language that uses function scope, any variables declared within a function are visible anywhere within that same function. But with block scope, the visibility of variables is confined to any given block (whether it's an if statement, where/for loop, etc) enclosed by curly braces.
3 thoughts on “Javascript: Block scope”