Skip to main content

Welcome to a Grasp lesson

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

Lesson 8

Understanding let, const, and var

This lesson is built with resources from youtube.com, medium.com and 1 more site.

Hello! Welcome back.

In our last lesson, we took a deep dive into how JavaScript manages memory. You learned that variables are essentially named labels for locations in memory, and we distinguished between the fast, orderly Stack (for primitives) and the flexible, larger Heap (for objects).

Today, we'll build directly on that foundation. Now that you know what a variable represents in memory, we'll learn the practical skill of how to declare them in your code. This lesson focuses on the three keywords you use to create variables: let, const, and the older var. Our goal is to declare variables using let, const, and var, and explain their scoping and reassignment differences. Understanding these differences is absolutely critical for writing modern, predictable, and bug-free JavaScript—the kind you'll need for Next.js and TypeScript.

A Quick Bit of History: var, let, and const

For many years, var was the only way to declare a variable in JavaScript. However, it had some confusing behaviors that could lead to unexpected bugs. In 2015, with a major update to the language (called ES2015 or ES6), let and const were introduced to provide a more robust and predictable way to declare variables.

To get a quick overview of this timeline, the following video provides some helpful context.

JavaScript Let, Const & Var: A Complete Guide

The video 'JavaScript Let, Const & Var: A Complete Guide' by Colt Steele starts by explaining the historical context of why let and const were introduced.

Watch the first minute and a half (from 00:12 to 01:25). This will set the stage for why we have three keywords instead of just one.

Now, let's explore the three crucial differences between these keywords.


1. Scope: Where is the Variable Accessible?

The most important difference between var, let, and const is their scope. Scope determines where a variable can be accessed in your code.

var: Function Scope

Variables declared with var are function-scoped. This means they are accessible anywhere within the function they are declared in, regardless of blocks like if statements or for loops inside that function. If declared outside any function, they become global variables.

let and const: Block Scope

let and const introduced a new, more precise type of scope: block scope. A block is any section of code enclosed in curly braces {...}. This includes if statements, for loops, and while loops. A variable declared with let or const only exists within the block it was declared in.

This might seem abstract, so let's look at a practical example that shows why this matters. The following video demonstrates a common bug caused by var's function-scoping behavior in a loop and how let solves it.

JavaScript var, let, and const explained

In this video, 'JavaScript var, let, and const explained', Kevin Powell provides a brilliant, practical demonstration of a scope-related bug and its fix.

Watch from 01:20 to 05:59. First, observe the 'weird results' when using var in a loop (from 01:20). Notice how the item variable from the inner loop 'leaks out' and overwrites the item variable in the outer loop. Then, see how simply changing var to let (from 04:33) fixes the problem entirely, because let creates a new variable for each block-scoped iteration of the loop.

As you saw, let's block scope prevents variables from "leaking" out of loops and conditionals, which is a major source of bugs with var. This is the primary reason why modern JavaScript development heavily favors let and const.


2. Reassignment and Redeclaration

The second major difference relates to whether you can change a variable's value or declare it again.

  • Reassignment: Changing the value of an already declared variable.
  • Redeclaration: Declaring a variable with the same name again in the same scope.

Here's how they compare:

Keyword Reassign? Redeclare? (in same scope)
var Yes Yes
let Yes No
const No No

Let's see this in code:

// --- var ---
var score = 80;
score = 85;       // ✅ Reassignment is OK
var score = 90;   // ✅ Redeclaration is also OK (this is confusing!)

// --- let ---
let level = 1;
level = 2;        // ✅ Reassignment is OK
// let level = 3; // ❌ Redeclaration throws an Error!

// --- const ---
const lives = 3;
// lives = 2;      // ❌ Reassignment throws an Error!
// const lives = 4; // ❌ Redeclaration throws an Error!

The const "Gotcha": Constant Reference, Not Constant Value

This is a critical concept that directly connects to our previous lesson on the Stack and Heap. When you declare a variable with const, it means the reference to the value cannot be changed.

  • For primitive types (stored on the Stack), this means the value is effectively constant.
    const PI = 3.14; You can't change this.
  • For reference types (objects and arrays stored on the Heap), it means the variable on the Stack will always point to the same object in the Heap. However, you can still change the contents of that object.

Watch this short clip that explains this nuance perfectly.

JavaScript Let, Const & Var: A Complete Guide

The 'JavaScript Let, Const & Var' video also has a great section explaining what const really means for objects and arrays.

Watch from 03:33 to 04:33. Notice how you can't reassign the people array to a new value, but you can push new items into it.

Here is a visual summary of the key differences we've covered so far. This kind of mind map can be very helpful for memorizing these rules.

var vs let vs const in JavaScript
This mind-map visually contrasts `var`, `let`, and `const`, highlighting their differences in scope (function vs. block), reassignment rules, and hoisting behavior. It's a great cheat sheet for the core concepts of this lesson.

3. Hoisting and the Temporal Dead Zone (TDZ)

Finally, let's explore a "deep theory" concept called hoisting. Hoisting is JavaScript's behavior of moving all declarations to the top of their scope before code execution. However, var, let, and const are hoisted differently.

var Hoisting

var declarations are hoisted and initialized with the value undefined. This means you can access a var before its declaration without an error—you'll just get undefined.

console.log(myVar); // Outputs: undefined
var myVar = "Hello!";

The JavaScript engine interprets this as:

var myVar; // Declaration is hoisted and initialized as undefined
console.log(myVar);
myVar = "Hello!"; // Assignment happens here

let and const Hoisting (The TDZ)

let and const declarations are also hoisted, but they are not initialized. They exist in a state called the Temporal Dead Zone (TDZ) from the start of the block until the declaration is encountered. Accessing a variable in the TDZ results in a ReferenceError.

// console.log(myLet); // ❌ ReferenceError: Cannot access 'myLet' before initialization
let myLet = "Hello!";

The TDZ is a good thing! It prevents you from accidentally using a variable before you've declared its value, making your code safer and more predictable.

JavaScript Hoisting Explained: var, let, const & Functions

To solidify your understanding of this advanced topic, the article 'JavaScript Hoisting Explained' provides clear code examples and a helpful comparison table.

Read the sections 'var Hoisting', 'let and const Hoisting', and 'Hoisting Comparison'. Focus on the code examples that show how the engine interprets hoisted code and the clear table comparing the behaviors.

Test your understanding!

What will be logged to the console in each of these three cases? Why?

// Case 1
console.log(a);
var a = 10;

// Case 2
console.log(b);
let b = 20;

// Case 3
const c = 30;
c = 40;
Show answer
  1. undefined: The declaration var a is hoisted to the top and initialized with undefined. The console.log(a) runs before the line a = 10 is executed.
  2. ReferenceError: The declaration let b is hoisted, but it remains in the Temporal Dead Zone (TDZ). You are trying to access b before its declaration line is reached, which results in an error.
  3. TypeError: You are trying to reassign a new value (40) to a variable declared with const. This is not allowed and will throw a TypeError: Assignment to constant variable.

Best Practices and Recommendations

With all this information, the modern JavaScript best practice is quite simple and is agreed upon by almost all developers.

Understanding Variable Declarations in JavaScript: var, let ...

The article 'Understanding Variable Declarations in JavaScript' provides a great summary of best practices.

Read the final 'Conclusion' section of this article. It sums up the modern approach perfectly.

The community consensus is:

  1. Avoid var. Its function scope and hoisting behavior are sources of confusion and bugs. There is no good reason to use it in modern codebases.
  2. Use const by default. This should be your go-to keyword. It signals that the variable's reference should not change, which makes your code easier to reason about.
  3. Use let only when you need to reassign a variable. This is common for things like loop counters or variables whose values need to change based on program logic.

By following this simple rule (const first, let if you must), you will write cleaner, safer, and more modern JavaScript.


Conclusion

Great work! You've just learned one of the most fundamental aspects of writing modern JavaScript. Mastering the differences between var, let, and const will save you countless hours of debugging down the road.

Key Takeaways:

  • Variables are declared using var, let, or const.
  • Scope: var is function-scoped, while let and const are block-scoped. Block scope is more predictable and helps prevent bugs.
  • Reassignment: var and let can be reassigned. const cannot.
  • The const rule: const guarantees that the variable's reference will not change. For objects and arrays, this means the content can still be modified.
  • Hoisting: var is hoisted and initialized to undefined. let and const are hoisted but are in a Temporal Dead Zone (TDZ) until declared, which throws an error if you access them early.
  • Best Practice: Use const by default, and let only when you know a variable's value needs to change. Avoid var.

In our next lesson, we will formally define JavaScript's primitive data types—string, number, boolean, null, and undefined. We'll explore them in detail and prepare to tackle the crucial difference between passing data by value versus by reference, a concept that builds directly on what you learned about the Stack, Heap, and const today.