Difference between var, let, and const keyword in JavaScript

Key takeaways:

  • The var keyword is function-scoped, hoisted and initialized with undefined. It allows re-declaration.

  • The let keyword is block-scoped, hoisted but not initialized. Accessing the let variables before declaration result in ReferenceError. It doesn’t allow re-declaration within the same scope.

  • The const keyword is also block-scoped, hoisted but not initialized. Once assigned, const cannot be reassigned; however, if it holds an object or array, the properties can still be modified.

  • The choice between var, let, and const depends on their scoping rules, hoisting behavior, and mutability.

JavaScript is known for its flexibility, which allows us to declare variables in different ways. However, each keyword—var, let, and const—has unique characteristics and is best suited for specific use cases. Understanding the differences between these keywords will help us write cleaner, more reliable code. In this Answer, we’ll learn about each keyword’s behavior and scope, with examples to see them in action.

The var keyword

It is the traditional variable declaration in JavaScript. The var keyword was the only way to declare variables in JavaScript before ECMAScript 6 (ES6) was introduced in 2015. While still usable, var has some limitations compared to let and const.

Characteristics of var

Let’s discuss some of the characteristics of the variable declaration using the var keyword.

Scope is the accessibility during runtime of variables, functions, or objects in a particular part of the code.

  • Scope: The var has function scope, meaning it is accessible throughout the function in which it is declared.

  • Hoisting: The var declarations are hoisted to the top of their scope and initialized with undefined.

  • Re-declaration: We can re-declare var variables without any error.

Example

Let’s see how var behaves in different scenarios:

function example() {
console.log(x); // Output: undefined (hoisted)
var x = 10;
if (true) {
var x = 20;
console.log(x); // Output: 20 (function scope)
}
console.log(x); // Output: 20 (no block scope)
}
example();

In the above code:

  • Line 2: The console.log(x) outputs undefined because x is hoisted but not initialized yet.

  • Lines 4–8: The var keyword has function scope, so x inside the if block reassigns x in the entire function.

The let keyword

With ES6, the let keyword was introduced to provide a more predictable variable declaration. It’s block-scoped and avoids many of the issues associated with var.

Characteristics of let

Let’s discuss some of the characteristics of the variable declaration using the let keyword.

  • Scope: The let has block scope, meaning it is limited to the block {} in which it is declared.

  • Hoisting: The let is hoisted but not initialized, so accessing it before declaration throws a ReferenceError.

  • Re-declaration: The let does not allow re-declaration within the same scope, making code more robust.

Example

Let’s observe the behavior of let in the following example:

function example() {
// console.log(y); // Uncommenting this line throws ReferenceError
let y = 10;
if (true) {
let y = 20; // This `y` is different from the outer `y`
console.log(y); // Output: 20 (block scope)
}
console.log(y); // Output: 10 (outer `y`)
}
example();

In the above code:

  • Line 2: Accessing y before its declaration causes a ReferenceError because let does not allow usage before initialization.

  • Lines 4–8: The let variable y inside the if block is scoped only to that block and doesn’t affect the outer y.

The const keyword

The const keyword is also block-scoped, similar to let, but with one major difference: variables declared with const cannot be reassigned after initialization. It’s ideal for values that should remain constant throughout the code.

Characteristics of const

Let’s discuss some of the characteristics of the variable declaration using the const keyword.

  • Scope: Similar to let, const is block-scoped.

  • Hoisting: The const is hoisted but, like let, it cannot be used before declaration.

  • Immutability: The const values cannot be reassigned, but note that if the value is an object or array, its properties or elements can still be modified.

Example

Here’s how const works in practice:

function example() {
const z = 10;
// z = 20; // Uncommenting this line throws TypeError: Assignment to constant variable
if (true) {
const z = 30;
console.log(z); // Output: 30 (block scope)
}
console.log(z); // Output: 10 (outer `z`)
}
example();

In the code above:

  • Line 2: We assign z the value 10. Reassigning it later would throw a TypeError.

  • Lines 4–8: Inside the if block, const z = 30 is block-scoped and doesn’t interfere with the outer z.

Modifying objects with const

While const prevents reassignment, it doesn’t make the variable’s content immutable if it’s an object or array:

const user = { name: "Alice" };
user.name = "Bob"; // Works because we're modifying a property, not reassigning the object
console.log(user); // Output: { name: "Bob" }

Comparison: var, let, and const

Here’s a quick comparison to summarize their differences:

var

let

const

Scope

Function

Block

Block

Hoisting

Yes, initialized as undefined

Yes, but uninitialized

Yes, but uninitialized

Re-declaration

Allowed

Not allowed

Not allowed

Reassignment

Allowed

Allowed

Not allowed

When to use each keyword?

Let’s discuss when to use which keyword.

  • Use var when working with legacy code or if compatibility with older JavaScript environments is required. Also, use var when we need to create a variable inside of a block and want to access the var in the whole function.

  • Use let for variables that will change over time and need to be block-scoped. Also, use let when we need to create a variable that should be only accessed inside the block.

  • Use const for values that should remain constant and only need to be initialized once. Also, use const when we need to create a variable that should only be accessed inside the block, and the value of the variable remains unchanged.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

Q

What will be the output of the following code?

var a = 5;
{
    let a = 10;
    console.log(a);
}
console.log(a);
A)
5
5
B)
10
5
C)
5
10
D)
10
10

Conclusion

Choosing the right variable declaration keyword is crucial for writing effective JavaScript code. While var has its uses, especially in legacy code, let and const provide better control over scope and immutability. Understanding these keywords’ behaviors will help us avoid pitfalls, making our code more predictable and easier to debug.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the difference between let and var in a for loop?

In a for loop, using let and var can lead to different behaviors due to scope.

  • let in for loops: When you use let to declare a loop variable, it is block-scoped, meaning each iteration has its own separate instance of the variable. This is particularly helpful when dealing with asynchronous functions within a loop, as each iteration maintains its own value of the variable.

    for (let i = 0; i < 3; i++) {
        setTimeout(() => console.log(i), 100); // Outputs: 0, 1, 2
    }
    
  • var in for loops: When you use var, the variable is function-scoped, so it is shared across all iterations. This means that by the time an asynchronous function runs, the variable may have changed to its final value in the loop.

    for (var i = 0; i < 3; i++) {
        setTimeout(() => console.log(i), 100); // Outputs: 3, 3, 3
    }
    

In general, let is preferred in for loops because it provides a new variable instance for each iteration, avoiding potential issues caused by var’s function-scoping.


Is var the same as const?

No, var and const are not the same, and they have key differences:

  • Scope: var is function-scoped, while const is block-scoped. This means const variables are limited to the block in which they are declared, whereas var variables are accessible throughout the function in which they’re defined.

  • Reassignment: Variables declared with var can be reassigned or redeclared within the same scope. On the other hand, const variables cannot be reassigned once assigned. Attempting to reassign a const variable results in an error.

    var x = 5;
    x = 10; // Allowed
    
    const y = 5;
    y = 10; // Throws an error
    
  • Use case: var is primarily used in legacy codebases, while const is the go-to keyword for variables meant to remain constant throughout the program. For modern JavaScript development, const is preferred whenever possible, as it signals that the variable’s value should not change, leading to more predictable code.

These differences make const and var useful in different scenarios, but in modern JavaScript, const is generally more favored for immutability and better control over scope.


Which keyword should I use for better performance?

let and const are generally preferred over var because they are block-scoped, reducing unexpected bugs and improving readability.


Free Resources