Day 2 - 100 JS Interview Questions : var let const
Interviewer : Tell me the difference between "var" "let" and "const"
In JavaScript, var
, let
, and const
are used to declare variables, but they behave differently in terms of scope, hoisting, and mutability.
Lets have a look at all 3 of them in depth. We will look into real life explaination of each of the 3 things, so as to understand properly, followed by a final comparison. It is believed that if you memorize anything via real life examples, it gets into you much more easier than anticipated.
Imagine a shared warehouse where workers in a factory can access all supplies stored anywhere in the building, regardless of whether they belong to their department. If a worker forgets what’s inside a box, they assume it’s empty until they look inside.
function warehouse() {
var box = "Tools"; // Declared inside the warehouse
if (true) {
var box = "Supplies"; // Redecared inside the same function
console.log("Inside if block:", box); // Supplies
}
console.log("Outside if block:", box); // Supplies (same box)
}
warehouse();
The var box
inside the if
block overrides the outer one because var
doesn’t care about blocks; it belongs to the whole function.
However, there is a key issue which we may encounter multiple times while using “var“. It can cause confusion and bugs if workers (developers) unintentionally overwrite shared variables.
Imagine you have a locker in a gym. For each and every locker, only you can access it, and only when you're in the locker room. Each locker is labeled with Locker Number (scoped) to prevent confusion and ensuring privacy.
function gym() {
let locker = "Shoes"; // Personal locker inside the function
if (true) {
let locker = "Water Bottle"; // New locker for the block
console.log("Inside if block:", locker); // Water Bottle
}
console.log("Outside if block:", locker); // Shoes (different locker)
}
gym();
Here, each let
locker is independent, even if they share the same name, because they belong to different blocks.
The Plus Point : Avoids accidental overwriting, like sharing lockers inappropriately.
In simple words, a safety box which contains valueables of someone. You may replace the box, but not the contents inside.
const safeDepositBox = ["Passport", "Jewelry"];
safeDepositBox.push("Cash"); // Add new item
console.log(safeDepositBox); // ["Passport", "Jewelry", "Cash"]
safeDepositBox = ["New Passport"]; // Error: Assignment to constant variable
Note that, while the safeDepositBox
itself cannot be reassigned, its contents can still be modified.
Re-Declarations & Re-Assignments
var
is like sharing a single whiteboard; anyone can write over what’s already there.
var a = 10;
var a = 20; // Allowed
console.log(a); // 20
let
& const
: Like having personalized notebooks—no one else can replace your notes.
let b = 10;
let b = 20; // Error: Identifier 'b' has already been declared
As far as re-assignment is concerned, var
& let
are like switching TV channels; you can change it whenever you want.
let c = 10;
c = 20; // Allowed
console.log(c); // 20
const
is like setting a TV channel lock—no changing it.
const d = 10;
d = 20; // Error: Assignment to constant variable
Use Cases
Suppose you are a project manager. You need an assistance for tracking your tasks.
function taskCounter() {
let count = 0; // Only for this block
count++; // Count one more task
console.log(`Total tasks: ${count}`);
}
taskCounter(); // Total tasks: 1
taskCounter(); // Total tasks: 1 (independent block-scoped variable)
A more simpler one! If you are making a software for some seat booking:
const seatMap = ["A1", "A2", "A3"];
seatMap.push("A4"); // Adding a new seat is allowed
console.log(seatMap); // ["A1", "A2", "A3", "A4"]
// seatMap = ["B1"]; // Error: Cannot reassign
Conclusion
Use
var
only in legacy projects or when working within function scope intentionally.Use
let
for variables that might change and should be block-scoped.Use
const
for variables that won’t be reassigned.
var | let | const | |
Scope | Function-scoped | Block-scoped | Block-scoped |
Re-declartion | Allowed | NA | NA |
Re-assignment | Allowed | Allowed | NA |
Hoisting | Hoisted - Initialized as ‘undefined ‘ | Hoisted - Not Initialized | Hoisted - Not Initialized |
The table above sums up everything which is discussed. By using the real life examples as in blog above, we may tend to undertstand this “notoriously basic“ question very easily. Above examples can also highlighted as it might reflect a different way of thinkin than the rest.
See you with the next question!