I have been programming in JavaScript
for a few months mostly using jQuery
. I understand closures and I have used them, however, I still can’t understand what is the difference between function level scope and block level scope in other languages such as C#. I have been trying to teach myself with no result on that subject. Could somebody explain me with some simple examples?
相关问题
- Is there a limit to how many levels you can nest i
- Sorting 3 numbers without branching [closed]
- How to toggle on Order in ReactJS
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
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.
You can see in the code above that the variables y, i, and inFor are declared either inside the if statement or inside the for loop. But, even though those variables are declared inside those separate "blocks", they are still visible to the rest of the function. This is because all of those variables are declared inside one function - which is what function scope is all about.
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.
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.
http://www.programmerinterview.com/index.php/javascript/javascript-block-scope/ http://www.programmerinterview.com/index.php/javascript/javascript-function-scope/
Prior to ES6 (the current version of JavaScript), JavaScript had only function level scope. That is, the following:
Is exactly equivalent to:
(As a matter of fact, what I've just shown is called "hoisting", which is exactly what JavaScript does: all variable declarations are hoisted to the top of the function; assignments are left where they are.)
In contrast, languages like C# have block level scope. This would result in a compile error:
But you can have this: