Variables declared with the “var” keyword can not have Block Scope.
Variables declared inside a block {} can be accessed from outside the block.
Example
{
var x = 2;
}
// x CAN be used here
Before ES2015 JavaScript did not have Block Scope.
Variables declared with the let keyword can have Block Scope.
Variables declared inside a block {} can not be accessed from outside the block:
Example
{
let x = 2;
}
// x can NOT be used here
2. Re declaring Variables
Re declaring a variable using the “var” keyword can impose problems.
Re declaring a variable inside a block will also re declare the variable outside the block:
Example
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
Re declaring a variable using the let keyword can solve this problem.
Re declaring a variable inside a block will not re declare the variable outside the block:
var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Lexical Scope :
Lexical Scoping defines how variable names are resolved in nested functions: inner functions contain the scope of parent functions even if the parent function has returned.