Difference Between const and let in JavaScript

Introduction

In JavaScript, there exist various approaches to define variables. The primary keywords utilized for variable declaration are var, let, and const.

Consider a scenario where we have developed a function that necessitates the use of a constant variable, one that will remain unchanged throughout the function’s execution. In this context, a variable declared using var or let is subject to modification, whereas a variable declared with const is immutable and will function correctly within our function.

Variable Declaration and Initialization

To hold any type of data, it is essential to declare a variable. Therefore, we will begin by defining a variable named var, followed by assigning a value to this variable.

Let us examine it with an example:

Example

var a;
a = "Example";
console.log(a)

Output:

Output

Example

As illustrated previously, we commenced by declaring the variable 'a' on the initial line, followed by the assignment of the string "Example" in the subsequent line.

The example provided employs a two-step method in which we first declare a variable and then proceed to initialize it. Nevertheless, it is possible to perform both the declaration and initialization in a single step, as illustrated in the following example:

Example

vara= "Example";
console.log(a);

In the earlier illustration, we utilized the var variable to create an instance; however, we can also declare and initialize variables using let and const.

Function-scope and Block-scope

Scope

The concept of "scope" pertains to the areas within our code where a variable can be accessed and where it cannot be utilized. The scope of a variable defines the sections of our code that have the ability to access it and those that do not. In JavaScript, scope is a key factor that differentiates let from const.

To better grasp it, let's look at an example -

Example

functionFunc() {
var a = "Example";
console.log(a);
}
Func();
console.log(a);

Output:

Output

"Example"
ReferenceError: a is not defined

In the provided example, the function Func serves the purpose of declaring a variable named "a" and subsequently printing its value to the console.

Upon invoking the function Func, the variable 'a' is displayed in the console. However, if we attempt to access it outside of the function, a referenceError is triggered. This occurs because 'a' is confined to the function's scope, rendering it inaccessible beyond the confines of the function.

Function scope

A variable with function scope pertains to a variable that is restricted for use exclusively within the function in which it is defined; it cannot be accessed from outside that function and will trigger a Reference Error if an attempt is made to access it externally.

Here is an illustration:

Example

functionmyage() {
var  age = 18;
console.log(age); 
}
myage ()
console.log(age);

Output:

Output

18
ReferenceError: age is not defined

In this illustration, we create the myage function and initialize a variable named age inside it. When the function is executed, it successfully prints the age variable to the console; however, attempting to access the variable from outside the function results in a reference error.

Block-scope

A block refers to any entity that is characterized by a set of opening and closing curly braces. It is defined as a combination of a pair of curly brackets.

A variable that possesses block scope is restricted to usage solely within the block where it is declared; it cannot be referenced from outside that block and will result in a Reference Error if an attempt is made to access it externally.

Here is an illustration:

Example

if(true) {
let name = "XYZ";
console.log(name); 
}
console.log(name);

Output:

Output

XYZ
ReferenceError: name is not defined

Inside the 'if' statement of the preceding example, we establish a variable named name and include an 'if' condition that evaluates to true. When we try to access the variable outside of the 'if' block, we encounter a Reference Error. However, the name variable successfully logs its value to the console.

What is the Let variable in JavaScript?

The most recent iteration of JavaScript, known as ES6, introduces two novel methods for variable declaration within the language. One such method is the use of the let keyword.

The following demonstrates the declaration of a variable using the let keyword:

Example

let name= "XYZ";

In the prior example, we created a variable using the let keyword and assigned it a string value of "XYZ".

It is important to note that re-declaration posed a problem with the var variable; however, the let variable addresses this concern by incorporating a distinct feature that prohibits the re-declaration of variables.

An example demonstrating the re-declaration of a variable defined with let:

Example

let name = "XYZ";
let name = "ABC";
console.log(name);

Output:

Output

SyntaxError: Identifier 'name' has already been declared

In the earlier example, we initially created a variable named "name", and subsequently, we attempted to define another variable using the identical name. However, when we tried to output this variable to the console, an error message appeared indicating "redeclaration of let name".

Scope of let variable

Block scope refers to the concept whereby a variable declared using let is only accessible within the block in which it was created. If there is an attempt to reference this variable outside of its designated block, a Reference Error will be triggered.

Using this as an example, let us comprehend it:

Example

let age = 28 ;
if(age > 18) {
let name = "XYZ";
console.log(name) 
}
console.log(name);

Output:

Output

XYZ
ReferenceError: name is not defined

The differentiation between let and const in JavaScript is illustrated in the example provided above. In the earlier example, we encountered an 'if' conditional statement featuring a variable named "age." Given that our 'if' condition holds true in this scenario, we proceed into the 'if' block. Within this block's scope, there exists another variable referred to as "name." We then print the "name" variable to the console while still within the 'if' block. However, this variable is inaccessible outside of the 'if' block, resulting in a 'ReferenceError' because of scope limitations.

Re-declaration of let variable

The primary concern with var variables was their restriction on re-declaring the same variable, although they allowed for the updating of the variable's value. The introduction of let variables helped us circumvent the problems that arose from the ability to re-declare variables.

To gain a deeper understanding of the re-declaration of the let variable, let us examine an example:

Example

let name = "XYZ";
let name = "ABC";
console.log(name);

Output:

Output

SyntaxError: Identifier 'name' has already been declared

In this example, we introduce a variable called 'name'. Subsequently, we create another variable with the same name and try to display its value on the console. This results in a syntax error being generated.

To understand the process of updating a let variable, let's examine the subsequent example:

Example

let name = "XYZ";
name = "ABC";
console.log(name);

Output:

In this scenario, we create a variable named "name" and assign it the value "XYZ". Subsequently, in the next line, we update the "name" variable with a new value: "ABC". When we later attempt to display the value of the "name" variable, the output on the console reflects the updated value of "ABC" instead of the original "XYZ".

Hoisting of let variable

Elevate the let variable to the top of its scope. However, it remains uninitialized. As a result, if we try to reference the let variable before its declaration, a syntax error will be triggered since there is no value available for it to return.

Let us see the example below:

Example

console.log(name); 
let name = "XYZ";

Output:

Output

ReferenceError

In this scenario, the variable name remains uninitialized when it is lifted to the beginning of the scope. Consequently, if we try to access it prior to its declaration, a ReferenceError will be triggered.

What is the Const variable in JS?

With the introduction of ES6, JavaScript has introduced two novel approaches for variable declaration. The first method employs the const keyword for defining variables that are constant. Here’s an example of a variable declared with const:

Example

const name = "XYZ";

The variable introduces a distinct feature that allows them to remain unchanged. Previously, there was a challenge associated with var variables concerning the declaration of constant variables. This challenge has been addressed with the implementation of const variables.

To illustrate, consider this example:

Example

const name = "XYZ";
name = "abcdef";
console.log(name);

Output:

Output

TypeError: invalid assignment to const 'name'

In the earlier illustration, we initiated our variable named "name" and assigned it a starting string value of "XYZ" for storage. Nonetheless, since the variable is defined as a const, we are unable to modify its value, which leads to a type error if we try to change the name variable.

const declarations are block-scoped

Const variables share the same block scope as let variables; however, they are not accessible beyond their defined context. To illustrate this concept more clearly, take a look at the following example:

Example

if(true) {
const name = "XYZ";
console.log(name);
}
console.log(name);

Output:

Output

ReferenceError: name is not defined

In the example provided, an 'if' statement is present along with a variable named 'name'. We can output the value of 'name' to the console by executing code within the 'if' statement. Nevertheless, due to the scope limitations of the const variable, an error occurs when we try to access the value of 'name' from outside the 'if' statement.

Const Variables cannot be modified or re-declared

Variables declared with the const keyword are immutable and cannot be altered or redeclared. This characteristic allows developers to write code that is free from modification-related errors when using const variables.

As an instance, let's see the update in const.

Example

const name = "XYZ";
name = "ABC"; 
console.log(name);

Output:

Output

TypeError: invalid assignment to const 'XYZ'.

In the initial line of the example, a variable named name is established, followed by the assignment of a value to the name variable.

It raises a TypeError when we try to output the name variable to the console, signifying that we cannot modify the const variable.

In order to understand the concept of re-declaration within the context of const, we can examine a specific example.

Example

const name = "XYZ";
const name = "ABC";
console.log(name);

Output:

Output

TypeError: invalid assignment to const 'name.'

In the initial line of the provided example, you will find the designation of a variable, which is subsequently declared once more in the line that follows.

The SyntaxError notification signifies that we cannot re-declare the const variable when we try to print the name variable to the console.

Hoisting of const

Moreover, the scope is broadened to encompass the const variable. Nevertheless, it remains uninitialized, meaning that utilizing the const variable prior to its declaration is impermissible and will result in a syntax error if an attempt is made. This occurs because the const variable lacks an assigned value to display.

Let’s take a look at an example to enhance our understanding:

Example

console.log(name); 
const name = "XYZ";

Output:

Output

ReferenceError

In this scenario, the const variable remains uninitialized even after being hoisted to the top of its scope. Consequently, if we try to access a variable name prior to its declaration, we encounter a ReferenceError.

Key Difference Between Let and Const in JavaScript

In JavaScript, the key differences between Let and Const lie in their scope and mutability. Let strikes a balance between flexibility and stability. Introduced in ES6, it is scoped to the block in which it is defined. It allows for modification but does not permit re-declaration. On the other hand, Const represents the most stringent option for variable declarations, making it ideal for values that need to remain unchanged throughout the program. Like Let, Const is also a feature of ES6 and is block-scoped; however, it cannot be altered or re-declared.

The difference between let and const in JavaScript is exemplified in the table below:

let const
let have the block scope. const variable has the block scope.
Moreover, it was raised to the peak of its scope yet failed to initialize. Moreover, it was raised to the top of its scope yet failed to initialize.
It cannot be re-declared; it can only be modified. It cannot be changed or re-declared.
It's a brand-new variable declaration method included in ES6. Additionally, it offers a new method of variable declaration seen in ES6.
Does not require initialization when declared. It can only be announced with the first being initialized.

Conclusion

In JavaScript, the keywords 'const' and 'let' are employed for declaring variables, yet they possess distinct characteristics. The scope of a variable defines the sections of the code where it can be accessed or where it is restricted from being accessed.

Recent approaches to variable declaration in JavaScript involve the use of 'let' and 'const'. Both of these keywords are hoisted; however, they do not initialize the variable at the time of declaration. The 'const' keyword is intended for variables that are not meant to be reassigned after their initial assignment, ensuring that their value remains constant throughout the program. Conversely, 'let' is utilized to declare variables that allow for reassignment, creating mutable bindings that can be updated as necessary.

The 'const' keyword promotes immutability, serving as a clear indication that the values assigned to such variables are not intended for change. In contrast, 'let' permits the modification of a variable's value. The choice between using 'let' or 'const' ultimately hinges on the specific requirements of your code. Use 'const' when you are certain that a variable's value will remain unchanged, and employ 'let' when you anticipate that a variable's value will need to be updated. Grasping these distinctions is crucial for developing JavaScript code that is both robust and easy to maintain.

Input Required

This code uses input(). Please provide values below: