DEV Community

Cover image for JavaScript let, var, and const: Understanding the Differences With Examples
BuildWithGagan
BuildWithGagan

Posted on • Edited on

1

JavaScript let, var, and const: Understanding the Differences With Examples

Introduction

When learning JavaScript, understanding the difference between let, var, and const is essential. These three keywords are used for variable declaration, but they behave differently. Using them correctly can improve the efficiency, maintainability, and security of your code. In this article, we will explore the differences between let, var, and const with practical examples and step-by-step explanations.


What Is var in JavaScript?

Before ES6 (ECMAScript 2015), var was the only way to declare variables in JavaScript. However, it has some drawbacks related to scope and hoisting.

Characteristics of var

  1. Function Scoped - A var variable is only accessible inside the function where it is declared.
  2. Hoisting - Variables declared with var are hoisted to the top of their scope and initialized as undefined.
  3. Can Be Redeclared and Updated - var allows reassigning and redeclaring the same variable without errors.

Example of var

function exampleVar() {
    var x = 10;
    if (true) {
        var x = 20; // Reassigns the same variable
        console.log(x); // Output: 20
    }
    console.log(x); // Output: 20 (because of function scope)
}
exampleVar();
Enter fullscreen mode Exit fullscreen mode

Explanation

  • var is function-scoped, so the value changes within the entire function.
  • Redeclaring var inside a block does not create a new variable; it modifies the existing one.

What Is let in JavaScript?

ES6 introduced let as a replacement for var to provide better scoping and avoid unintended behavior.

Characteristics of let

  1. Block Scoped - Variables declared with let are confined to the block {} where they are defined.
  2. Not Hoisted Like var - let is hoisted but remains in the "temporal dead zone" until it is initialized.
  3. Cannot Be Redeclared in the Same Scope - Unlike var, let cannot be declared twice in the same scope.

Example of let

function exampleLet() {
    let x = 10;
    if (true) {
        let x = 20; // This creates a new variable inside the block
        console.log(x); // Output: 20
    }
    console.log(x); // Output: 10 (because of block scope)
}
exampleLet();
Enter fullscreen mode Exit fullscreen mode

Explanation

  • let respects block scope, so the inner x does not affect the outer x.
  • It prevents accidental overwriting of variables.

What Is const in JavaScript?

The const keyword is used to declare variables whose values cannot be reassigned.

Characteristics of const

  1. Block Scoped - Like let, const is restricted to the block in which it is defined.
  2. Must Be Initialized - A const variable must be assigned a value at the time of declaration.
  3. Immutable Reference - You cannot reassign a const variable, but if it holds an object or array, its properties or elements can be modified.

Example of const

function exampleConst() {
    const x = 10;
    // x = 20; // Error: Assignment to constant variable

    const person = { name: "John" };
    person.name = "Doe"; // Allowed because object properties can be modified
    console.log(person.name); // Output: Doe
}
exampleConst();
Enter fullscreen mode Exit fullscreen mode

Explanation

  • const prevents reassigning variables but allows modifying object properties.
  • It is best for values that should not change, such as configuration settings.

Key Differences Between var, let, and const

Feature var let const
Scope Function Block Block
Hoisting Hoisted as undefined Hoisted but in TDZ Hoisted but in TDZ
Redeclaration Allowed Not Allowed Not Allowed
Reassignment Allowed Allowed Not Allowed (except for objects/arrays)

Common Mistakes and Best Practices

1. Avoid Using var

// Instead of this:
var count = 5;

// Use this:
let count = 5;
Enter fullscreen mode Exit fullscreen mode

2. Use const When a Variable Should Not Change

// Instead of this:
let PI = 3.14;

// Use this:
const PI = 3.14;
Enter fullscreen mode Exit fullscreen mode

3. Use let for Variables That Change

let userAge = 25;
userAge = 26; // Allowed
Enter fullscreen mode Exit fullscreen mode

FAQs

1. Can I use var in modern JavaScript?

Yes, but it is not recommended due to its function-scoping behavior, which can lead to unexpected issues. let and const are preferred.

2. When should I use const over let?

Use const for variables that should not be reassigned, and let when you need to update the value.

3. What happens if I declare a let variable twice in the same scope?

You will get a syntax error because let does not allow redeclaration.

4. Can I modify an object declared with const?

Yes, but you cannot reassign the object itself. You can modify its properties.

const user = { name: "Alice" };
user.name = "Bob"; // Allowed
// user = { age: 25 }; // Error
Enter fullscreen mode Exit fullscreen mode

5. Why is const still hoisted?

Like let, const is hoisted but remains in the temporal dead zone (TDZ) until it is initialized.


Conclusion

Understanding let, var, and const is crucial for writing clean, efficient, and bug-free JavaScript code.

  • Use var only if necessary (legacy code).
  • Use let for mutable variables.
  • Use const for immutable variables (or references).

By applying these best practices, you can improve the maintainability and readability of your JavaScript projects. Happy coding!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

If this post resonated with you, feel free to hit ❤️ or leave a quick comment to share your thoughts!

Okay