In Javascript, var scopes are rather different than in other programming languages. A variable created with the “var” prefix, if its been created inside a function, it will only exists in that function.
For example:
[javascript]
var result = 0;
var sum = function(a, b) {
var result = 0;
result = a+b;
return result;
};
console.log(sum(2,3));
console.log(result);
[/javascript]
This code will print in console:
[html]
5
0
[/html]
In Javascript (before let command existed) the block doesn’t have a scope, so if we declare with VAR a variable within block, it will be included in the function where resides the block. This will change with the introduction of let statement.
From Javascript 7, we will be able to declare a variable whose scope will be the block itself, and this will be possible thanks to let, so if we write this code:
[javascript]
function letTest() {
let my_scope = 1;
if(1 == 1) {
let my_scope = 2; // variable within if block scope
console.log(my_scope); // 2
}
console.log(my_scope); // 1
}
[/javascript]
The official doc about the let command can be found in Mozilla MDN Javascript Reference.
As Javascript 7 is not integrated in all browsers you must be careful about using it now. You can check Mozilla’s compatibility table to check if the major browsers allow the statement already. In order to use ‘let’ statement you should include your JS code inside the following brackets:
[html]
<script type="application/javascript;version=1.7">
</script>
[/html]