Javier Núñez Fernández Full Stack Web Engineer

'Let' statement in Javascript 7

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:


var result = 0;
var sum = function(a, b) {
  var result = 0;
  result = a+b;
  return result;
};
console.log(sum(2,3));
console.log(result);

This code will print in console:



5
0

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:



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
}

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:


<script type="application/javascript;version=1.7">

</script>