Let , var and const
Hello, everyone!
Today, I will discuss the significance of let,
var,
and const
in JavaScript. This topic holds great importance during interviews and can sometimes even perplex seasoned developers. I kindly request all of you to buckle up and join me on this enlightening and captivating journey as we delve into these concepts and gain a clear understanding of them.
difference between var and let:-
Allow me to elucidate the distinction between var
and let
through a simple and captivating example. Let's consider a scenario where your name is Harsh, and that is how the entire world knows you. However, within the confines of your home, you are referred to as Mike. In this analogy, your name "Harsh" represents a global example or var
, while being called Mike at home symbolizes a local instance or let.
This analogy helps us grasp the concept of variable scope and how var
and let
differ in their visibility and accessibility within different contexts.
Let's further explore the analogy. If you were to step outside your home, nobody would recognize you as Mike since your global identity is known as Harsh. This aligns with the scenario of a global variable in programming. However, it's worth noting that even though your local name is Mike, within the confines of your home, nobody will address you as Harsh. Similarly, in programming, a local variable retains its value and is accessible only within its defined scope. So, while the global variable is recognized universally, the local variable remains confined to its specific context, just like your name being restricted to your home environment.
var name = "Harsh";
console.log(name); //Harsh
const getA = () => {
let name = "Mike";
console.log(name); //Mike
};
getA();
Let's consider the second situation. In this case, you have only one name, Harsh, and it is universally recognized throughout the world. Since there is no local variable or alternate name (such as Mike) within your home, there is no conflict or confusion. This scenario aligns with the concept of a global variable in programming. When only a global variable is defined and there are no local variables, the global variable retains its recognition everywhere, just like your name Harsh being acknowledged universally. It provides a clear understanding that in the absence of local variables, the global variable remains consistent and unambiguous, allowing for seamless recognition regardless of the context.
var name = "Harsh";
console.log(name); //Harsh
const getA = () => {
console.log(name); //Harsh
};
getA();
Let's explore the third situation. In this case, you don't have a global name, but you do have a local name, which is Mike. Within the confines of your home, everyone addresses you as Mike. However, outside your home, where a global name is expected, nobody would be able to recognize you since you lack a universal or global identity. This scenario reflects the concept of a local variable without a corresponding global variable in programming. The local name, Mike, is limited to the specific scope of your home, and without a global name, there is no recognition or visibility beyond that particular context.
console.log(name); //Error
const getA = () => {
let name = "Mike";
console.log(name); //Harsh
};
getA();
Indeed, this example provides a clear understanding of the scope of var
and let
when utilized in code. It illustrates the concept through a relatable analogy, allowing for a comprehensive grasp of their functionalities. By distinguishing between global and local variables, we can comprehend how var
and let
operate within different scopes. With this explanation, any remaining confusion regarding the scope of let
and var
should be resolved, providing a solid foundation for further understanding and implementation.
Variable Shadowing
Now let's delve into the concept of variable shadowing, using the same example of Mike as the local name or let
and Harsh as the global name or var.
Variable shadowing occurs when a local variable shares the same name as a global variable. In this case, within the confines of your home, you are referred to as Mike (local variable), while globally, you are known as Harsh (global variable). Here, the local variable, Mike, shadows or overrides the global variable, Harsh, within its specific scope.
This concept of variable shadowing highlights the importance of variable scoping and understanding which variable takes precedence within specific contexts.
Let's explore the concept of variable shadowing in the context of having a global name Harsh and a local name Mike. In this scenario, your local name, Mike, takes precedence within its scope, effectively shadowing the global name, Harsh. Variable shadowing occurs when a local variable shares the same name as a global variable, causing the local variable to overshadow or override the global variable within its specific field. It's important to note that variable shadowing is confined to its scope and does not impact the visibility or accessibility of the global variable outside of that scope. Therefore, within the designated environment where the local name is recognized, the global name remains hidden, but once you venture beyond that scope, the global name regains its prominence.
var name = "Harsh";
console.log(name); //Harsh
const getA = () => {
let name = "Mike";
console.log(name); //Mike
};
getA();
Let's explore another situation regarding variable shadowing. Imagine a scenario where you don't have a global name, but you have a local name defined in two different places: your office and your home. In this case, even if the variable is being shadowed in both local scopes, there will be no conflict or adverse effects.
Since the local names (let variables) are individually defined within their respective scopes (office and home), there is no clash or ambiguity. Each local name exists independently within its environment, without interfering with each other or causing any conflicts.
This example demonstrates that variable shadowing within separate local scopes does not pose any problems because the local names are confined to their specific contexts. As a result, you can have distinct local names in different places without any negative consequences or overlapping values.
{
let name = "Harsh";
console.log(name); //Harsh
} // In javascript {} don't create a scope they are just to show example.
const getA = () => {
let name = "Mike";
console.log(name); //Mike
};
getA();
Let's explore the third situation involving variable shadowing. In this case, you define a name globally in both scopes. Despite the global variable being defined in multiple scopes, there will be no conflict because each variable exists as a global entity within its scope.
When a name is defined globally in separate scopes, it is considered legal variable shadowing. The global variables in each scope do not conflict with each other as they are both valid within their respective scopes. Each global variable retains its separate scope and remains accessible within that specific context.
Therefore, in this scenario, you can have the same name defined globally in multiple scopes without any conflict. Each global variable will be recognized and accessible within its scope, demonstrating the concept of legal variable shadowing.
{
var name = "Harsh";
console.log(name); //Harsh
}
const getA = () => {
var name = "Mike";
console.log(name); //Mike
};
getA();
console.log(name); //Harsh
Let's consider another situation that represents illegal variable shadowing. Imagine you have defined a variable named "name" using let
within a specific scope. However, if you attempt to shadow or redeclare it using var
within a higher part of that same scope, it will result in an error.
const getA = () => {
let name = "Mike";
console.log(name);
if (true) {
var name = "Harsh"; //Error "Identifier 'name' has already been declared"
}
};
getA();
The reason for this error is that var
does not respect block-level scope like let
or const
. Instead, var
is function-scoped. As a result, when the code encounters the var
declaration inside the if
statement, it clashes with the existing name
variable defined using let
in the same scope.
This showcases that attempting to shadow a variable with var
in a higher part of the same scope where it is already defined with let
is illegal and leads to a declaration error. It underscores the importance of understanding variable scoping rules and avoiding such illegal variable shadowing scenarios.
Execution of var and let -
In JavaScript, when we run the code, a process called hoisting occurs. During hoisting, variable declarations are moved to the top of their respective scopes, and variables are automatically initialized with the value of undefined
. However, this behavior specifically applies to variables declared using var
.
Variables declared with var
have function scope or global scope, and their declarations are hoisted to the top of their enclosing function or the global scope. This means that even if a variable is declared and initialized later in the code, it can still be accessed and its value will be undefined
before its actual assignment.
console.log(a); //undefined
var a = "Harsh";
When we define a variable using let
instead of var
, it exhibits a different behavior. With let
, the variable is also hoisted to the top of its scope, but it does not have an automatic initialization to undefined
like var
variables. Instead, it enters a zone called the Temporal Dead Zone (TDZ).
The Temporal Dead Zone is a phase in the code where the variable exists but cannot be accessed or assigned any value until its actual declaration is encountered. If you try to access the variable within the TDZ, it will result in a ReferenceError
.
console.log(a); //Error "Cannot access 'a' before initialization"
let a = "Harsh";
const
If we talk about const then some major points should be in mind when we are defining something with const.
You cannot declare a variable without initialization it
You cannot change the value of a variable declared with const anywhere or in any scope.
The hoisting property is similar to let hoisted but not initialized with undefined.
I hope this blog helped you understand the concept of let var and const and the major difference and confusion between them and if you have find any wrong concept or if anything is missing let me know I will try to fix it.
You can contact me on twitter or via email
Subscribe to my newsletter
Read articles from Harsh Pandey directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by