let javascript meaning code example

Example 1: javascript var and let

// var has function scope.
// let has block scope.

function func(){
  if(true){
    var A = 1;
    let B = 2;
  }
  A++; // 2 --> ok, inside function scope
  B++; // B is not defined --> not ok, outside of block scope
  return A + B; // NaN --> B is not defined
}

Example 2: let in javascript

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

let x = 1;

if (x === 1) {
  let x = 2;

  console.log(x);
  // expected output: 2
}

console.log(x);
// expected output: 1

Example 3: vars with let in it javascript

let /*Var name*/ = /*what is equals*/

Example 4: let javascript

var i = "global";
function foo() {
    var i = "local"; // Otra variable local solo para esta función
    console.log(i); // local
}
foo();
console.log(i); // global

Tags:

Misc Example