JavaScript Let and Const

Introduction to Let and Const

The introduction of 'let' and 'const' in ECMAScript 2015 (ES6) brought significant changes to variable declaration in JavaScript. These keywords offer block-level scoping and immutability, enhancing code predictability and maintainability.


Using 'let' for Variables

The 'let' keyword allows you to declare variables with block scope, meaning they are limited to the block, statement, or expression they are defined in.

Try yourself
        
            
// Using 'let' for Variables
function letExample() {
    if (true) {
        let x = 10;
        console.log(x); // Output: 10
    }
    console.log(x); // Error: x is not defined (outside of the block scope)
}

        
    

Using 'const' for Constants

The 'const' keyword is used to declare variables that cannot be reassigned. However, the value can still be mutable if it is an object or an array.

Try yourself
        
            
// Using 'const' for Constants
function constExample() {
    const PI = 3.14;
    PI = 22/7; // Error: Assignment to constant variable.
    
    const user = { name: 'John', age: 30 };
    user.age = 31; // Valid, as user is an object and properties can be modified.
    user = { name: 'Jane', age: 25 }; // Error: Assignment to constant variable.
}

        
    

Benefits of Using 'let' and 'const'

The introduction of 'let' and 'const' has several benefits:

Try yourself
        
            
// Benefits of Using 'let' and 'const'
// Block-level Scope: Variables are limited to the block in which they are defined
// Immutability: 'const' prevents reassignment, ensuring data integrity

// Example demonstrating block-level scope
function blockScopeExample() {
    let a = 5;
    if (true) {
        let a = 10;
        console.log(a); // Output: 10
    }
    console.log(a); // Output: 5
}

// Example demonstrating immutability
function immutabilityExample() {
    const PI = 3.14;
    PI = 22/7; // Error: Assignment to constant variable.
    
    const user = { name: 'John', age: 30 };
    user.age = 31; // Valid, as user is an object and properties can be modified.
    user = { name: 'Jane', age: 25 }; // Error: Assignment to constant variable.
}

        
    

Summary

The introduction of 'let' and 'const' in ECMAScript 2015 (ES6) brought significant changes to variable declaration in JavaScript. These keywords offer block-level scoping and immutability, enhancing code predictability and maintainability.