Understanding var, let, and const in JavaScript: A Simple Guide
Hey there fellow code enthusiasts! 🚀 In our coding adventure, one golden rule always shines through: nail the basics!
Whether it’s picking up a new programming language or any other skill in life, a solid grasp of the fundamentals is our secret weapon for long-term success. 🛠️ So, in this blog, we’re going back to the basics of JavaScript — but trust me, it’s anything but basic! We’re diving deep into the three musketeers of variable declaration: var, let, and const. 🧐
You know, I’ve been on the hot seat for countless interviews, even for senior frontend roles, I’ve seen the questions about var
, let
, and const
pop up more often than you'd think! 🤔
So, today, we’re going to unravel the mysteries behind these three and get you prepped and confident for your next coding interview or project. Let’s get started! 💻
What is this var, let, and const in Javascript first of all?
So, like in any other programming language, we need variables to store some data and in Javascript, we have three different ways to do so.
Now, you’ll say why three different ways for a single task?
Hold on, we’ll cover everything!
🕒 Before ES6: We just had var
. But as JavaScript evolved, let
and const
came along to solve var
's issues.
💬 Breaking It Down
Let’s note one thing first, in the whole blog we’ll be diving deep into var
and let
for simplicity, as const
and let
are almost similar with only a single difference which we will cover at last.
var: The old-school way. It’s flexible but can lead to bugs.
Function-level scope
Re-declarable
let — The new approach. More controlled and less error-prone.
Block-level scope
Not re-declarable
Declaration of variables via var
and let
Let’s check the code below —
var a = "Hello"
var a = "world"
console.log(a)// Output: "world"
let a = "Hello"
let a = "world"
console.log(a) // SyntaxError: Identifier 'a' has already been declared.
We can clearly see here that while re-declaring a new variable with the same name we got the error with the let
keyword.
This flexibility of re-declaring a variable with the same name always made the program prone to bugs and thus it was later fixed with a let
keyword.
🔍 Scope and Accessibility
When we hear about the scope of any variable, it means the boundary in which any variable is accessible once defined. Like If you define any variable inside any function it can’t be accessed outside it.
Let’s check the code below —
if(true) {
var a = 10;
}
console.log(a) // Output: 10
We can access our variable a
outside the if statement, as it was scoped to the main function and still accessible in the scope of the function, now check another code -
if(true) {
let a = 10;
}
console.log(a)
When we try to do the same, we get the ReferenceError of our variable not defined.
Now let’s first understand Block-scoping vs Function-scoping.
Block Scope — Whenever a variable is defined with let/const its scope is limited to the block which is usually defined by opening and closing curly brackets {}. This is called Block-level scoping, where variables are only available under the curly braces.
Whereas in the case of variables defined through var,
it doesn’t care about any brackets and extends its scope to the function where it’s defined.
| That means the variable exists everywhere in the function if defined via var
keyword despite of blocks present there but in case of variables defined via let
they’re restricted to the block where they’re defined.
⬆️ Hoisting
Now here comes something that every interviewer wants to hear from you when listening about the difference between var
, let
, and const
.
Hoisting is the concept of javascript, in which whenever we declare any variable or function its definition is hoisted on the top when the program starts its execution.
Variables declared with the var
keywords are subject to hoisting. If we declare a variable (but do not initialize it) at the end of the function, the JavaScript runtime will move it to the top of its scope and, therefore, there will be no complaint by the runtime if we use that variable before being declared.
But in the case of variables declared via let
, the case is different. It’s not hoisting. This means you cannot use a variable unless it is declared and initialized.
🆚 let
vs const
in Javascript.
As we read earlier variable declaration by both the let
and cons
are the same with only a single difference that once a variable is declared via const
it can’t be re-defined or in other words the value is always constant and it can’t be changed later on.
Let’s understand via code —
let a = 10;
console.log(a) // Output: 10
a = 20;
console.log(a) // Output: 20
/* ------------------------------------------------------------------- */
const b = 10;
console.log(b) // Output: 10
b = 20;
console.log(b) // TypeError: Assignment to constant variable.
Here we can clearly see that we’re not allowed to change the value of a variable once defined which has been declared via const
.
Now let’s check another code -
const x = {
a: 10,
b: 20
}
console.log(x.a) // Output: 10
x.a = 50
console.log(x.a) // Output: 50
However, we can see here that we were able to successfully change the value of x.a
despite being defined via const
. Now the point to keep in mind is that again we were never able to change the value of x
instead we changed the property inside an object since it’s still possible to be a property of the object. If you want to prevent the updation of the internal property too, you can try something like Object.freeze(x)
, and then the internal property will also be prevented from updating.
📌 Summary
And that’s var
, let
, and const
for you! They may seem small, but they're mighty important.
Let’s recap once again —
Variables defined via
var
are function-level scoped whereas variables defined vialet
orconst
are block-level scoped.Variables can be re-defined again if created via
var
, but it’s not possible if created vialet
orconst
.Hoisting is only possible for variables created through
var
.
🌟 Enjoyed the read? I’d love to hear your thoughts! Share your takeaways and let’s start a conversation. Your insights make this journey richer for all of us.
👏 If you found this helpful, a clap or two would mean the world — it helps more folks find these guides!
🔜 What’s next? I’m already brewing the next topic, packed with more insights and a-ha moments. Stay tuned!
🙏 A big thank you for spending time with my words. Your support fuels my passion for sharing knowledge.
👋 Until next time, keep coding and keep exploring!
💬 Let’s stay connected! Follow me on Hashnode for more adventures in coding: https://thenomadtechie.hashnode.dev/