difference between let" and "var" in JavaScript

 

The main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope).

following is the comprehensive example of both type of variables 

function someFun() {
  var someVar = "someVar";
  let someLet = "someLet";

  console.log(someVar, someLet); // someVar someLet

  {
    var someVar1 = "resttr"
    let someLet = "letuuu";
    console.log(moo, baz); // resttr letuuu
  }

  console.log(someVar1); // resttr
  console.log(someLet); // ReferenceError
}

someFun();

Tags:

Share:

Related posts