TL;DR

console.log(b);  // 100
let a = 10;
var b = 100;

console.log(a);  // referenceError: can't access a before initialized.
let a = 10;
var b = 100;
  • In case of var scope is global, but for let and const they have different memory block that we can’t access before we put some values in it.
  • Time since when let variable is hoisted till its assigned is know as Temporal dead zone.
console.log("hehe")
console.log(b);
var a = 10;
var b = 100;
// hehe
// 100

console.log("hehe")
console.log(b);
let a = 10;
let a = 100;
// syntexError : can't re-initialize a.


const b;
// syntexError : missing initializer in const declaration

const c = 10;
c = 1000;
// typeError: assignment to constant variable

what is block?

block is pair of curly braces {} used to group statements together. also know as Compound statement

Why we use Blocks ?

so we can use multiple statements in JavaScript where it expects a single statement. if(condition) statement;. Here we can use block as a compound statement or it can be a single statement.

What is block scope?

a block scope is scope that allows us to access variables and functions declared inside this block.

{
var a = 10;
let b = 20;
const c = 30;
console.log(a);  // 10
console.log(b);  // 20
console.log(c);  // 30
}

console.log(a);  // 10
console.log(b);  // referenceError
console.log(c);  // program exited.

what is shadowing?

shadowing occurs when a variable declared within a certain scope (e.g., a block or function) has the same name as a variable declared in an outer scope. The inner variable “shadows” the outer variable, meaning that within the inner scope, the inner variable takes precedence, and the outer variable is inaccessible.

var a = 1000;
{
  var a = 10;
  console.log(a); // 10
}
console.log(a); // 10
//--------------------------
let a = 1000;
{
  let a = 10;
  console.log(a); // 10
}
console.log(a); // 1000
//--------------------------
const a = 1000;
{
  const a = 10;
  console.log(a); // 10
}
console.log(a); // 1000

what is illegal shadowing ?

It refers to a situation where a variable declared with let or const in a block scope attempts to shadow a variable declared with var in the same scope, which can result in a syntax error. This primarily occurs because var declarations are function-scoped and hoisted to the top of their containing function or global scope, while let and const are block-scoped and not hoisted in the same way.

let x = 10;
{
  var x = 20; // syntexError
}
// --------------------
let x = 10;
function a() {
  var x = 20; // valid
}
// -------------------
var x = 10;
{
  let x = 20; // valid
}