Skip to main content

Welcome to a Grasp lesson

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

Lesson 22

Understanding let, const, and Why var is Outdated

Recommended resources

Hello! Welcome to the fourth module of our course. We've spent the last few modules refreshing your HTML and CSS skills, focusing on building the structure and visual presentation of a website. You've successfully built and styled a responsive personal profile site, which is a fantastic foundation.

Now, we shift our focus to JavaScript, the language that brings websites to life. In this module, you'll learn how to add interactivity, manipulate page content dynamically, and handle user actions.

This first lesson tackles a fundamental concept in modern JavaScript: how we declare variables. Your goal is to declare variables using let and const, and explain why var is avoided in modern JavaScript. Understanding this is crucial because it helps prevent common bugs and makes your code more predictable and maintainable—aligning with your goal to understand the "why" behind best practices.

1. Setting Up for JavaScript Practice

Let's get your project ready for some JavaScript. We'll continue working on the personal profile site you built in the previous modules.

  1. Open your project in VS Code.

  2. Create a new Git branch for this module's work. This keeps your JavaScript experiments separate from your completed CSS work.

    git checkout main
    git checkout -b module-4-js-concepts
    
  3. Create a new file named variables.js in your project's root directory.

  4. Link the script in your index.html file. Place the <script> tag just before the closing </body> tag.

    <!-- at the bottom of index.html -->
      ...
      <script src="variables.js"></script>
    </body>
    </html>
    

Why at the bottom? Placing the script tag here ensures that the HTML content is fully loaded and parsed by the browser before the JavaScript tries to run. This prevents errors that can occur if your script tries to find an HTML element that doesn't exist yet.

Now you can write code in variables.js, save it, and see the output in your browser's developer console (usually opened with F12 or Ctrl+Shift+I).


2. The Old Way: The Problem with var

For many years, var was the only way to declare a variable in JavaScript. However, it has some quirky behaviors that can lead to unexpected bugs. The most significant issue is its scoping rule.

To see this in action, watch the first part of this video from Programming with Mosh.

JavaScript Let vs Var vs Constant | Mosh

This video provides a clear and practical demonstration of why var can be problematic, focusing on how it behaves inside a simple for loop.

Watch from 00:23 to 03:35. Pay close attention to the for loop example. Notice how the variable i, declared with var, is accessible outside the loop block where it was defined. This is a behavior you generally want to avoid.

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

This "leaking" out of blocks is a common source of bugs.


3. The Modern Way: Block-Scoped let and const

To fix the problems with var, ES6 (a major update to JavaScript in 2015) introduced two new keywords for declaring variables: let and const. Their most important feature is that they are block-scoped.

This means a variable declared with let or const is only accessible inside the block ({ ... }) where it is defined.

This next video from Web Dev Simplified gives a comprehensive comparison of all three keywords.

Differences Between Var, Let, and Const

This video walks through the key differences between var, let, and const, covering scope, re-assignment, hoisting, and how const works with objects.

Watch from 00:44 to 06:58. This covers the most important concepts: Block Scope (00:44 - 02:48): See how let and const fix the scope problem of var. Re-declaration (02:48 - 04:06): Understand why let and const prevent you from accidentally re-declaring a variable. Hoisting (04:06 - 05:26): Learn about another strange var behavior that let and const solve. const Immutability (05:26 - 06:58): Clarify the common misconception about what const makes constant.

Hands-On: Trying it Yourself

Let's solidify those concepts. Add the following code to your variables.js file, save, and check the console.

1. Scope

if (true) {
  var oldSchoolVar = "I'm available everywhere";
  let newSchoolLet = "I'm only inside the block";
  const newSchoolConst = "Me too, only inside the block";
}

console.log(oldSchoolVar); // This works!
// console.log(newSchoolLet); // This will cause an error.
// console.log(newSchoolConst); // This will also cause an error.

Uncomment the last two lines one by one. You'll see a ReferenceError because newSchoolLet and newSchoolConst don't exist outside the if block. This is the predictable behavior we want.

2. Re-assignment and Re-declaration

  • let allows you to update the value, but not re-declare it.
  • const (constant) does not allow you to update the value or re-declare it.
let season = "Summer";
season = "Winter"; // This is okay. The value can change.
console.log(season);

// let season = "Spring"; // This is NOT okay. It throws a SyntaxError because 'season' has already been declared.

const year = 2024;
// year = 2025; // This is NOT okay. It throws a TypeError because you can't assign to a constant variable.
console.log(year);

3. The const Caveat: Objects and Arrays

A common point of confusion is that const does not make objects or arrays fully "immutable". It just means the variable cannot be reassigned to a new object or array. You can still change the properties of the object or the elements of the array.

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

// person = { name: "Jane", age: 31 }; // NOT allowed. Can't re-assign the variable.

person.age = 31; // This IS allowed. We are modifying a property, not re-assigning the 'person' variable itself.
console.log(person); // { name: "John", age: 31 }

4. Summary and Best Practices

You've now seen the critical differences between var, let, and const. For writing clean, modern, and predictable JavaScript, follow these simple rules:

  1. Avoid using var. Its function-scoping and hoisting behavior are sources of bugs.
  2. Default to const. Use it for any variable whose value will not be reassigned. This makes your code safer by preventing accidental changes.
  3. Use let only when you need to reassign a variable's value. This is common for loop counters or variables that track changing state.

This visual mind map is a great summary of everything we've covered.

var vs let vs const in JavaScript
This mind map provides a quick visual reference for the key differences between `var`, `let`, and `const`, covering their scope, hoisting, and re-assignment rules.

For a deeper textual dive into these topics, the articles from javascript.info and dev.to are excellent resources that you can review now or bookmark for later.

The old "var"

For a very detailed explanation, 'The old "var"' from The Modern JavaScript Tutorial is an excellent, though more technical, read.

This is optional reading. Focus on the sections "‘var’ has no block scope", "‘var’ tolerates redeclarations", and "‘var’ variables can be declared below their use" to reinforce the key concepts.


Conclusion

In this lesson, you've taken the first and most important step into modern JavaScript. You now understand the fundamental differences between var, let, and const, and more importantly, you have a clear set of best practices for declaring variables.

Key Takeaways:

  • var is function-scoped, which can cause variables to "leak" out of blocks like if statements and loops.
  • let and const are block-scoped, which provides more predictable and bug-resistant behavior, similar to many other programming languages.
  • const should be your default choice to prevent accidental reassignment. Use let only when a variable's value needs to change.

In the next lesson, we will continue building on these fundamentals by exploring functions. You'll learn the modern "arrow function" syntax and see how it builds upon the block-scoping concepts you learned today.