Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 4

Var, Let, and Const: Scoping and Hoisting

Recommended resources

Following our exploration of JavaScript's data types and coercion rules, we now turn our attention to the containers that hold this data: variables. While you've been using variables for years, the introduction of let and const in ES6 brought crucial distinctions from the original var. These differences, especially in scoping and a concept called "hoisting," are not just academic—they are a frequent source of questions in technical interviews and QCM exams.

This lesson will provide a precise, exam-focused review of var, let, and const. Our goal is to differentiate them based on their scoping rules, their behavior regarding re-declaration and re-assignment, and the subtle but critical concept of hoisting. Mastering these nuances is key to both writing predictable code and acing tricky exam questions.

Scope: Where Variables Live

The most fundamental difference between var, let, and const is their scope—the region of your code where a variable can be accessed.

  • var is function-scoped: When you declare a variable with var, it is accessible anywhere within the function it was declared in, regardless of blocks like if statements or for loops. If declared outside any function, it becomes globally scoped.
  • let and const are block-scoped: These variables are only accessible within the curly braces {} block where they are defined. This is a much more intuitive and less error-prone behavior.

Consider this classic example:

function scopeTest() {
  if (true) {
    var varVariable = "I am var";
    let letVariable = "I am let";
    const constVariable = "I am const";
  }

  console.log(varVariable);  // Outputs: "I am var"
  // console.log(letVariable); // Throws ReferenceError: letVariable is not defined
  // console.log(constVariable); // Throws ReferenceError: constVariable is not defined
}

scopeTest();

The var variable "leaks" out of the if block, while let and const are confined to it. This block-scoping behavior is a primary reason for preferring let and const in modern JavaScript.

For a detailed walkthrough of these scoping rules, please consult the following article from GeeksforGeeks.

Difference between var, let and const keywords in JavaScript

This article clearly explains the scoping differences with simple, effective code examples.

Please read the following sections: Declaring with var: This section demonstrates the function-scoped nature of var. Block Scope with let: Focus on this section to see a clear example of how let is confined to its block. Immutability with const: This introduces const and notes that it is also block-scoped, just like let.


Re-declaration and Re-assignment

The keywords also differ in whether you can change a variable's value or declare it again in the same scope.

  • var: Allows both re-declaration and re-assignment in the same scope.
  • let: Allows re-assignment but not re-declaration in the same scope.
  • const: Allows neither re-declaration nor re-assignment. It must be initialized at the time of declaration.

This brings up a crucial point about const with objects and arrays. Declaring an object with const means the reference to the object cannot be changed. However, the properties of the object itself can still be modified.

const person = { name: "Alice", age: 30 };

// This is ALLOWED: mutating the object's properties
person.age = 31; 
console.log(person.age); // Outputs: 31

// This is NOT ALLOWED: re-assigning the constant variable
// person = { name: "Bob", age: 40 }; // Throws TypeError: Assignment to constant variable.

This is a common point of confusion and a perfect topic for a QCM question.

The GeeksforGeeks article you just reviewed also covers these rules thoroughly. Take a moment to read the relevant sections.

Difference between var, let and const keywords in JavaScript

This reading will solidify your understanding of the mutability rules, including the important nuance for const objects.

Please read the following sections: Re-declaring Variables: This section provides code snippets that clearly show what is and isn't allowed for each keyword. Constant Arrays and Objects: Pay close attention to this part, as it explains the distinction between re-assigning the variable and modifying its contents.


Hoisting and the Temporal Dead Zone

Hoisting is a JavaScript mechanism where variable and function declarations are conceptually moved to the top of their scope before code execution. However, how they are hoisted differs significantly.

A simple visual illustrating that accessing a `var`-declared variable before its declaration line results in `undefined`, while doing the same for a `let`-declared variable results in an error.

Here's the breakdown:

  1. var: Declarations are hoisted and are initialized with a default value of undefined. This means you can access a var variable before its line of declaration without an error—you'll just get undefined.

    console.log(myVar); // Outputs: undefined
    var myVar = 10;
    
  2. let and const: Declarations are also hoisted, but they are not initialized. They exist in a state known as the Temporal Dead Zone (TDZ) from the start of their scope until the point where they are declared. Accessing them within the TDZ results in a ReferenceError.

    // console.log(myLet); // Throws ReferenceError: Cannot access 'myLet' before initialization
    let myLet = 10;
    

This behavior is intentional, as it prevents bugs that arise from using a variable before its value has been set.

To truly understand why this happens, it helps to understand the JavaScript execution context, which has a creation phase and an execution phase. The following video provides one of the clearest explanations of this process.

Javascript Interview Questions ( Var, Let and Const ) - Hoisting, Scoping, Shadowing and more

This video from RoadsideCoder brilliantly explains the concept of hoisting by first detailing the JavaScript execution context. Understanding this two-phase process makes the behavior of var, let, and const much clearer.

Please watch the segment from Hoisting and Execution Context. The presenter first explains the "creation" and "execution" phases, which is the foundation for hoisting. He then demonstrates exactly how var is hoisted versus how let and const are hoisted into the Temporal Dead Zone (TDZ).

For a final reinforcement, the article below from DEV Community frames these concepts as interview questions, which aligns perfectly with your exam preparation.

10 Core Questions on Hoisting, Scope & Closures - DEV Community

This article provides concise, exam-style explanations of hoisting and the Temporal Dead Zone.

Focus on the first two questions: Question 1 explains the classic var hoisting behavior. Question 2 gives a clear and practical definition of the TDZ for let and const.


Synthesis: A Summary Table

We've covered scope, re-assignment, and hoisting. This table provides a quick-reference summary of all the key differences, making it an excellent tool for last-minute revision.

A comprehensive table comparing `var`, `let`, and `const` across scope, re-declaration, re-assignment, initialization, hoisting, and recommended use cases.

As a modern best practice, and a good rule to follow for clean code:

  • Use const by default for all variable declarations.
  • Use let only when you know you will need to re-assign the variable's value.
  • Avoid using var in new code to prevent scope and hoisting-related bugs.

Conclusion

In this lesson, we have dissected the three ways to declare variables in JavaScript. Understanding these distinctions is not just for passing exams, but for writing robust, modern, and professional-grade code.

Key Takeaways:

  • Scope: var is function-scoped. let and const are block-scoped ({}).
  • Re-assignment: var and let can be re-assigned. const cannot, though the contents of a const object or array can be mutated.
  • Hoisting: var is hoisted and initialized to undefined. let and const are hoisted but remain in the Temporal Dead Zone (TDZ), throwing a ReferenceError if accessed before declaration.
  • Best Practice: Prefer const, use let when necessary, and avoid var.

Now that we have a firm grasp on how to declare and manage variables, our next lesson will focus on putting them to work by interacting with the web page itself. We will cover the Document Object Model (DOM) and learn how to use JavaScript to manipulate HTML elements and respond to user events.