Lexical Scoping Example

by Julien Etienne

JavaScript

// We are in the first scope 

const canNotReAssign = 500;
let canReAssignLet = 300;
var canReAssignVar = 200;
const sameNameConst = 2000; // this is in the 1st scope 

if (true) {
  // We are in the second scope 

  // canNotReAssign = 400    //  This will cause an error if you comment it out.
  canReAssignLet = 100 // All good.
  canReAssignVar = 100 // same as let.
  const sameNameConst = 2000;
}

// Back to the first scope
console.log(canNotReAssign) // 500 
console.log(canReAssignLet) // 100
console.log(canReAssignVar) // 100 
console.log(sameNameConst) // 2000   Because const declaired with the same name in the second scope doesn't affect the first scope or any other scopes.


// A block scope is anything with brackets
{
// This is a block scope 
  const balbla = 'Hello World'
}

if(1 + 1 === 2){
// This is a block scope 

}

for(let i = 0; i < 5; i++){
// This is a block scope 
}

// const and let are block scoped which means you can not access variables declaried in a scope from its outer scope

// But var is different, var can be accessed anywhere


{
var greeting = 'Hey';
const beQuiet = 'Please be quite'
}

console.log(greeting) // Hey 
// console.log(beQuiet)  // This will throw an error for const and let because it dosen't exist in the outer scope of the above block.