Start Coding

Topics

JavaScript let and const

In modern JavaScript, let and const are two powerful keywords for declaring variables. They were introduced in ECMAScript 6 (ES6) to address some limitations of the traditional var keyword.

The let Keyword

let allows you to declare block-scoped variables. Unlike var, variables declared with let are only accessible within the block they're defined in.


if (true) {
    let x = 10;
    console.log(x); // 10
}
console.log(x); // ReferenceError: x is not defined
    

This block-scoping behavior helps prevent unintended variable leaks and makes your code more predictable.

The const Keyword

const is used to declare constants - variables whose values cannot be reassigned after initialization.


const PI = 3.14159;
PI = 3.14; // TypeError: Assignment to a constant variable
    

However, it's important to note that const doesn't make the value immutable. For objects and arrays, the properties or elements can still be modified.

Key Differences and Best Practices

  • Use const by default for variables that won't be reassigned.
  • Use let for variables that will be reassigned.
  • Avoid using var in modern JavaScript code.
  • Both let and const are hoisted but not initialized, creating a "temporal dead zone".

Temporal Dead Zone (TDZ)

The TDZ is a behavior where variables declared with let and const cannot be accessed before their declaration.


console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 5;
    

This behavior helps catch potential bugs early in development.

Block Scope vs Function Scope

While var is function-scoped, let and const are block-scoped. This means they're limited to the block (enclosed by curly braces) where they're defined.


function example() {
    if (true) {
        var x = 1; // Function-scoped
        let y = 2; // Block-scoped
        const z = 3; // Block-scoped
    }
    console.log(x); // 1
    console.log(y); // ReferenceError
    console.log(z); // ReferenceError
}
    

Conclusion

Understanding let and const is crucial for writing clean, maintainable JavaScript code. These keywords provide better scoping rules and help prevent common programming errors. As you continue your JavaScript journey, make sure to practice using them in various scenarios.

For more on JavaScript fundamentals, check out our guides on JavaScript Variables and JavaScript Scope.