❗var has no block scope❗️
JS ⟩ variable ⟩ var ⟩ has no block scope
var in block doesn't have block scope, cannot shadow let variable in the outer enclosing scope.
var hoisting - var is hoisted to top of enclosing function scope.
let redeclaration not allowed even in sloppy mode❗️ - let doesn't allow redeclaration.
function f() {
let a = 1; // let declaration
// var a = 2; // <----- var declaration is hoisted here❗️
// which raises a redeclaration SyntaxError.
// (let doesn't allow redeclaration)
// block scope
{
// ⭐️ `var` doesn't have block scope,
// cannot shadow `let` variable in outer enclosing scope.
var a = 2;
// ^
// ⛔ SyntaxError: Identifier 'a' has already been declared
}
// another block
{
let b = 3;
// ❗ although `var` doesn't have "block scope",
// we can't put let/var in the same block either.
var b = 4;
// ^
// ⛔ SyntaxError: Identifier 'b' has already been declared
}
}Last updated
Was this helpful?