What Is the Difference Between var, let, and const in JavaScript?

In JavaScript, var, let, and const are used to declare variables, The main difference are as follows.

Scope

var: Variables declared with var are function scoped. They are visible throughout the whole function in which they are declared. If declared outside any function, they become global variables.

let and const: Variables declared with let and const are block scoped. They are only accessible within the function block where they are defined. This makes them more predictable and safer to use, especially in situations like loops or conditional statements.

Hoisting

var: Variables declared with var are hoisted to the top of their scope during the compilation phase. This means you can use the variable before it is declared, but the value assigned to it will not be hoisted.

let and const: Like var, let and const are hoisted, but unlike var, they are not initialized until the interpreter reaches the line where they are declared. Attempting to access the variable before its declaration results in a Reference Error.

Reassignment

var: Variables declared with var can be redeclared and reassigned.

let: Variables declared with let can be reassigned, but not redeclared in the same scope.

const: Variables declared with const cannot be reassigned or redeclared after their initial assignment. However, keep in mind that const is not immutable when it comes to objects or arrays; it prevents the variable reference from being changed, but the properties or elements of the object or array can still be modified.

Simple example as follows.

Using var

var a = 1;

if (true) {

 var a = 2;
 console.log(a); // Outputs 2
}

console.log(a); // Outputs 2, the value of 'a' is modified globally

Using let

let b = 1;

if (true) {
  let b = 2;
  console.log(b); // Outputs 2
}

console.log(b); // Outputs 1, the value of 'b' remains unchanged in the outer scope

Using const

const c = 1;

// c = 2; // Error: Assignment to a constant variable

In modern methods, it is advisable to use let and const over var. Use let when the variable needs to be reassigned and use const when the variable should not be reassigned.

This will improve the code readability, maintainability, and reduces the risk of bugs related to variable scoping.