let or var javascript 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: var vs let js

let: //only available inside the scope it's declared, like in "for" loop, 
var: //accessed outside the loop "for"

Example 3: let and var difference

function run() {
  var foo = "Foo";
  let bar = "Bar";

  console.log(foo, bar);

  {
    let baz = "Bazz";
    console.log(baz);
  }

  console.log(baz); // ReferenceError
}

run();

Example 4: vars with let in it javascript

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

Tags:

Misc Example