Const Let And Var In Javascript

Posted on November 24, 2024 by Vishesh Namdev
Python C C++ Javascript Java
Variables in Javascript

Global Scope and Local Scope Variables

Global scope and Local scope Variables

1. var
Purpose: The traditional way to declare variables before ES6 (2015). Less commonly used now due to its quirks.
Scope: Function-scoped (if declared inside a function) or globally scoped (if declared outside any function).
Reassignment: Allowed.
Behavior: Variables declared with var are hoisted to the top of their scope, meaning they can be accessed even before they are declared (initialized to undefined).

    // Using var
    var name = "John";
    name = "Doe"; // Allowed: Reassignment is fine.
    
    console.log(x); // Undefined: x is hoisted but not initialized.
    var x = 10;
    
    if (true) {
      var message = "Hi!";
    }
    console.log(message); // Prints: Hi! (var is not block-scoped).

2. let
Purpose: Used for variables that need to be reassigned or are block-scoped.
Scope: Block-scoped (accessible only within the block in which it's defined).
Reassignment: Allowed.
Behavior: Variables declared with let are not hoisted in the same way as var and have a "temporal dead zone" (accessing them before their declaration results in a ReferenceError).

let age = 25;
age = 26; // Allowed: Reassignment is fine.
          
if (true) {
    let greeting = "Hello!";
    console.log(greeting); // Prints: Hello!
}
console.log(greeting); // Error: greeting is not defined (block scope).

3. Const
Purpose: Used to declare variables that cannot be reassigned.
Scope: Block-scoped
Reassignment: Not allowed after the initial assignment.
Behavior: If the value is an object or array, its properties/elements can be modified, but the reference to the object cannot change.

const PI = 3.14;
PI = 3.15; // Error: Assignment to constant variable.
                
const obj = { name: "Alice" };
obj.name = "Bob"; // Allowed: Object properties can be changed.
obj = {}; // Error: Cannot reassign the object.

Key difference between const, let and var

Global scope and Local scope Variables