Both i
-variables are in the same scope, because JavaScript variables traditionally have functional scope
.
Functional scope :
Functional scope means Variables are known within the function it is declared in, from the moment they are declared onwards.
Functionally scoped variables are created like this :
var myVariable = "Some text";
Functional scope can be understood like this :
// i IS NOT known here
function doSomething() {
// i IS NOT known here
for (var i = 0; i < bar; i++) {
// i IS known here
}
// i IS known here
}
// i IS NOT known here
Block scope
The most recent JavaScript specs now also allow block Scope : Variables are known within the block it is declared in, from the moment they are declared onwards.
Block scope variables are created like this :
let myVariable = "Some text";
Block scope can be understood like this :
// i IS NOT known here
function doSomething() {
// i IS NOT known here
for (let i = 0; i < bar; i++) {
// i IS known here
}
// i IS NOT known here
}
// i IS NOT known here
The difference between both scopes
To understand the difference between functional scope and block scope, consider the following code :
// i IS NOT known here
// j IS NOT known here
function loop(arr) {
// i IS NOT known here
// j IS NOT known here
for( var i = 0; i < arr.length; i++ ) {
// i IS known here
// j IS NOT known here
};
// i IS known here
// j IS NOT known here
for( let j = 0; j < arr.length; j++ ) {
// i IS known here
// j IS known here
};
// i IS known here
// j IS NOT known here
}
// i IS NOT known here
// j IS NOT known here
Here, we can see that our variable j
is only known in the first for loop, but not before and after. Yet, our variable i
is known in the entire function from the moment it is defined onward.
Is it safe to use block scope variables today?
Whether or not it is safe to use today, depends on your environment :
If you're writing server-side JavaScript code (Node.js), you can safely use the let
statement.
If you're writing client-side JavaScript code and use a transpiler (like Traceur), you can safely use the let
statement, however your code is likely to be anything but optimal with respect to performance.
If you're writing client-side JavaScript code and don't use a transpiler, you need to consider browser support.
Today, Feb 23 2016, these are some browsers that either don't support let
or have only partial support :
- Internet explorer 10 and below (no support)
- Firefox 43 and below (no support)
- Safari 9 and below (no support)
- Opera Mini 8 and below (no support)
- Android browser 4 and below (no support)
- Opera 36 and below (partial support)
- Chome 51 and below (partial support)
How to keep track of browser support
For an up-to-date overview of which browsers support the let
statement at the time of your reading this answer, see this Can I Use
page.