Saturday, July 01, 2017

Let it be...


Definition :

The let statement declares a block scope local variable, optionally initializing it to a value.

What different between var and let ?

It is mathematical statement.Remember in Math class, our teacher always mention let , for example:
If we let A be the statement "You are rich" and B be the statement "You are happy", then the negation of "A or B" becomes "Not A and Not B."
The question already answered in : Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?

The different , notice the code below is using var, once you define same variable in local scope in second time , it will overwrite  the variable in global scope,


function varTest() {
  var x = 1;
  if (true) {
    var x = 2;  // same variable!
    console.log(x);  // 2
  }
  console.log(x);  // 2
}

Using let, help to identify which belong to which.
function letTest() {
  let x = 1;
  if (true) {
    let x = 2;  // different variable
    console.log(x);  // 2
  }
  console.log(x);  // 1
}
For details please refer to : let