Let’s Understand the Difference Between let, const, and var in JavaScript
As a fellow JavaScript enthusiast, I know how fascinating it can be to navigate the world of variable declarations. When I first started my coding journey in JavaScript, I encountered three little words: let
, const
, and var
. They seemed innocent enough, but little did I know what power they held and the impact they could have on my Code.
Now, after countless hours of coding and debugging, I can say from my own experience Understanding the differences between these three keywords is crucial for writing clean, efficient, and bug-free code. In this article, we will dive deep into the dissimilarities between let
, const
, and var
, explaining when and how to use them appropriately. And I want to share this knowledge with you, my fellow developers.
You can create variables in JavaScript using var
,let
and const
a But what's the difference between these three?
To understand that, you need to learn the following three important concepts in JavaScript: Blocks, Scope, and Hoisting.
Blocks :
{
// This is a block
const greeting = "Hello JavaScript ";
console.log(greeting);
}
Here you can use curly braces {}
to group statements together as a single unit within functions, loops, or conditional structures and create a block. You can create even nest blocks within other blocks.
function greet() {
// This is a block
const greeting = "Hello World";
console.log(greeting);
if (greeting == "Hello World") {
// This is a nested block
const x = 0;
}
}
You’ll usually use blocks to define the body of a function, the body of an if statement, or the body of a loop.
Blocks introduce a new scope for your variables. But what is a scope?
Scope :
The scope of a variable is the region of the program where the variable is accessible and can be referenced. In other words, it defines where the variable is valid and can be used.
Let’s understand that with the help of an example.
{
let x = 2;
console.log(x); // 2
}
console.log(x); // Uncaught ReferenceError: x is not defined
When you try to print the let
variable outside of the scope of the block it was declared in, JavaScript throws an error saying that x
is not defined. This means that let
variables only live inside the scope in which they are defined. Or the scope of let
the variable ends when you exit the block in which it is defined in.
This means that if you try to access it outside of its scope, JavaScript will throw an error.
Similarly, for const
variables:
{
const x = 2;
console.log(x); // 2
}
console.log(x); // Uncaught ReferenceError: x is not defined
const
variables have the same scope as let
variables, i.e., the block in which they were defined in.
Note that you cannot access const
and let
variables before they are declared, even in the same block.
{
console.log(x); // ERROR: Cannot access 'x' before initialization
console.log(y); // ERROR: Cannot access 'y' before initialization
const x = 2;
let y = 2;
}
The Temporal Dead Zone (TDZ) is a behavior in JavaScript that occurs when you try to access a variable before it is declared using let
or const
. During the TDZ, attempting to access the variable results in a runtime error, specifically a "ReferenceError."
In JavaScript, there are two types of scope: global scope and local scope. When you declare a variable or function outside of any function or block, it is considered to be in the global scope.
// Global scope
let globalVariable = "I'm a global variable";
function globalFunction() {
console.log("I'm a global function");
}
console.log(globalVariable); // Output: I'm a global variable
globalFunction(); // Output: I'm a global function
However, if you declare a variable within a scope (that is not the global scope), it is considered to be in a local scope.
// Global scope
let globalVariable = "I'm a global variable";
function globalFunction() {
// Local scope or function scope
let localVariable = "I'm a local variable";
}
console.log(globalVariable); // Output: I'm a global variable
console.log(localVariable); // Uncaught ReferenceError: localVariable is not defined
Hoisting
Now, let’s take a look at the scope of var
variables.
{
var x = 2;
console.log(x); // 2
}
console.log(x); // 2
Surprisingly, JavaScript does not throw any error and executes perfectly in this case! This is because of something known as hoisting.
Hoisting occurs when variable declarations and function declarations are moved to the top of their containing scope during the compilation phase before the code is executed. In this case, the var
variable declaration is hoisted to the global scope that is why you are able to access it outside of the block
Now, let’s take a look at how var
variables are hoisted in the function scope.
function hello() {
console.log(greeting); // undefined
{
{
var greeting = "Hello";
}
console.log(greeting); // Hello
}
console.log(greeting); // Hello
}
console.log(greeting); // ERROR: greeting is not defined.
In the above case, the greeting
the variable is hoisted to the nearest function scope instead of the global scope. It will first look for a function scope if available, if not, it will be hoisted to the global scope.
Again, greeting
will behave as if it was declared at the top of the function. Thus, you can access it anywhere within the scope of the function.
1. Var :The Classic Variable Declaration
In the early days of JavaScript, var
was the only keyword available for variable declarations. It has a function scope, which means it is limited to the function in which it is declared. If var
is declared outside any function, it becomes a global variable accessible throughout the entire script. This can lead to unintended consequences and pollute the global scope, making code maintenance challenging.
// Example 1: Using var
var x = 10;
console.log("Initial value of x:", x); // Output: Initial value of x: 10
function updateValue() {
var x = 20; // This is a different variable x, scoped to the function
console.log("Inside function - x:", x); // Output: Inside function - x: 20
}
updateValue();
console.log("Outside function - x:", x); // Output: Outside function - x: 10
2. let :Block-Scoped Variables
With the introduction of ES6 (ECMAScript 2015), the let
keyword came into play. Unlike var
, let
is block-scoped, which means it is limited to the block in which it is declared, such as a loop or an if
statement. Block-scoping ensures that the variable's scope is confined within the relevant block, reducing the risk of unexpected behavior and making code easier to reason about.
// Example 2: Using let
let y = 30;
console.log("Initial value of y:", y); // Output: Initial value of y: 30
function updateValueWithLet() {
let y = 40; // This is a different variable y, scoped to the function
console.log("Inside function - y:", y); // Output: Inside function - y: 40
}
updateValueWithLet();
console.log("Outside function - y:", y); // Output: Outside function - y: 30
3. const:Immutable Constants
The const
keyword also emerged with ES6, and as the name suggests, it is used to declare constants. Once a variable is declared with const
, its value cannot be changed or reassigned. This ensures that the variable remains constant throughout the code execution. It is essential to note that while the variable's value cannot be changed, its properties (for objects and arrays) can still be modified.
// Example 3: Using const
const z = 50;
console.log("Value of z:", z); // Output: Value of z: 50
// Uncomment the line below to see the error
// z = 60; // Error: Assignment to constant variable
Therefore, in modern JavaScript (after ES6), you are recommended to use let
and const
instead of var
for declaring variables to prevent unintended side effects.
To write clean and maintainable code, follow these best practices:
- Use
let
for variables that need to be reassigned within their scope. - Use
const
for values that should remain constant throughout the code. - Avoid using
var
in modern JavaScript development, aslet
andconst
offer better scoping and error prevention.
FAQs:-
Q1: Can I use let
and const
in all modern browsers?
A1: Yes, let
and const
are fully supported in all modern browsers, including IE11 and above.
Q2: Is there any performance difference between let, const, and var ?
A2: No, there is no significant performance difference between them. The choice should be based on scoping requirements and code readability.
Q3: Can I reassign the properties of a const object or array?
A3: Yes, while you cannot reassign a const
variable itself, you can modify its properties if it is an object or an array.
Q4: What happens if I use var within a block?
A4: Variables declared with var
within a block are still function-scoped, and their value will be accessible outside the block.
Q5: Can I use let
and const
in other programming languages?
A5: The let
and const
keywords are specific to JavaScript and may not be available in other programming languages.