← all writing

Variable Declaration In JavaScript

Variable declaration in JavaScript goes through three phases:

  1. Declaration phase
  2. Initialisation phase
  3. Assignment phase

1. Declaration Phase

2. Initialization Phase

3. Assignment Phase

Example

// Declaration Phase
var name;
let age;
const PI = 3.14;
 
// Initialization Phase
name = 'John';
age = 25;
 
// Assignment Phase
name = 'Alice';   // Reassigned with a new value
age = 30;         // Reassigned with a new value
 
// Constants cannot be reassigned (const assignment phase)
// PI = 3.14159; // Error: Assignment to constant variable

Walking through var name = 'Deepak'

Let's describe each phase for the statement var name = 'Deepak';.

Declaration Phase

Initialization Phase

Assignment Phase

Example

// Declaration Phase (Hoisting)
var name;          // The variable `name` is declared in the current scope and hoisted to the top.
 
// Initialization Phase
name = 'Deepak';   // The variable `name` is assigned the value 'Deepak'.
 
// Assignment Phase (Not applicable in this example)
// name = 'Alice'; // Reassigned with a new value if needed.

let vs var during these phases

In JavaScript, both let and var declarations go through the same phases of variable creation: the Declaration Phase and the Initialization Phase. However, there is a crucial difference between them when it comes to the value they hold during these phases.

For var declarations:

  1. Declaration Phase: The variable is declared and hoisted to the top of its scope. At this point, it exists in memory and is assigned a value of undefined.
  2. Initialization Phase: During this phase, the variable remains undefined until the code execution reaches the line where it is explicitly assigned a value.

Example

console.log(name);          // Output: undefined
var name = 'Deepak';
console.log(name);          // Output: Deepak

For let declarations:

  1. Declaration Phase: The variable is declared and hoisted to the top of its block scope, but unlike var it is not initialized. It is in a "temporal dead zone" until the point of its declaration, and trying to access it before the declaration results in a ReferenceError.
  2. Initialization Phase: When code execution reaches the declaration line, the variable is initialized — to undefined if no value was given, or to the assigned value otherwise. After this point it leaves the temporal dead zone and behaves like any other variable.

Example

console.log(name);          // ReferenceError: Cannot access 'name' before initialization
let name = 'Deepak';
console.log(name);          // Output: Deepak