Variables in JavaScript – Understand var, let and const
Quick Answer: JavaScript uses var, let and const to declare variables. A variable stores a value that your program can use. Use const by default, let when reassignment is needed, and avoid var in modern JavaScript.
1. The Problem: Managing Student Records
Imagine you manage student records for 1,000 students. Each student has a name, marks and attendance status.
How will you store these values and update them safely? Think about what happens when the application grows.
We can start by writing values directly inside our program.
Example 1: Student details without variables
This example prints student information directly.
console.log("Student: Priya");
console.log("Marks: 85");
console.log("Present: Yes");
console.log("Student: Arjun");
console.log("Marks: 72");
console.log("Present: No");
Expected output
Student: Priya Marks: 85 Present: Yes Student: Arjun Marks: 72 Present: No
This works, but it becomes difficult to manage.
What goes wrong as records increase?
- We repeat the same values in many places.
- Changing a student's marks becomes difficult.
- We cannot easily reuse a value in another calculation.
- Related information becomes harder to understand.
- Small changes can create mistakes across the application.
Now imagine handling 1,000 students instead of two. We need a better way to store and update information.
2. What Is a Variable in JavaScript?
Variable = a named place where a value is stored.
We give that place a name. Then we use the name whenever we need its value.
For our student records, we can create variables for names, marks and attendance.
Example 2: Store student details using variables
let studentName = "Priya";
let marks = 85;
let isPresent = true;
console.log(studentName);
console.log(marks);
console.log(isPresent);
Expected output
Priya 85 true
Now we can use these values anywhere in the same accessible scope. We can also update values when the student's information changes.
How the three declarations fit into our student records
Animation 01 · Student data storage
Three declarations, three storage rules
Watch each student value enter its own named storage slot.
let studentName "Priya" can change when needed.let marks 85 can become 90 after an update.const PASS_MARKS 40 stays fixed in this example.The animation highlights separate named values and their declaration rules.
3. Understanding var, let and const
JavaScript provides three keywords for declaring variables. They differ in scope, reassignment and redeclaration.
3.1 var – The older declaration keyword
var was used widely in older JavaScript code. It allows reassignment and redeclaration in the same scope.
It is function-scoped, not block-scoped. This difference can create unexpected results inside conditions and loops.
Example 3: Declare and update a student value using var
var studentName = "Priya";
console.log(studentName);
studentName = "Lakshmi";
console.log(studentName);
var studentName = "Arjun";
console.log(studentName);
Expected output
Priya Lakshmi Arjun
Notice that we declared studentName again. JavaScript allows this with var in the same scope.
Important: Redeclaring a variable accidentally can hide earlier values. This is one reason modern JavaScript code generally avoids var.
3.2 let – Use it when a value can change
let allows reassignment. It does not allow redeclaration in the same scope.
It is block-scoped. A block is a section of code inside curly braces.
This makes let useful for values that change during program execution.
Example 4: Update a student's marks using let
let marks = 85;
console.log("Original marks:", marks);
marks = 90;
console.log("Updated marks:", marks);
Expected output
Original marks: 85 Updated marks: 90
We declared marks once. Then we assigned a new value to it.
Remember: Use let when a variable needs a new value later.
3.3 const – Use it when reassignment is not allowed
const declares a variable that cannot be reassigned. You must provide its value when declaring it.
It is also block-scoped. It does not allow redeclaration in the same scope.
For our student records, the passing marks can be a constant in this example.
Example 5: Store fixed passing marks using const
const PASS_MARKS = 40;
let studentMarks = 85;
console.log("Passing marks:", PASS_MARKS);
console.log("Student marks:", studentMarks);
studentMarks = 90;
console.log("Updated student marks:", studentMarks);
Expected output
Passing marks: 40 Student marks: 85 Updated student marks: 90
We can change studentMarks. We cannot assign another value to PASS_MARKS.
Important: const prevents reassignment. It does not make objects or arrays deeply immutable. Their contents may still change.
4. var vs let vs const: Side-by-Side Comparison
This table summarizes the main differences between all three keywords.
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function scope | Block scope | Block scope |
| Reassignment | Allowed | Allowed | Not allowed |
| Redeclaration in same scope | Allowed | Not allowed | Not allowed |
| Initialization required | No | No | Yes |
| Hoisting behavior | Initialized as undefined | Uninitialized until declaration | Uninitialized until declaration |
| Modern usage | Usually avoid | Use when reassignment is needed | Default choice when reassignment is not needed |
Terms to remember
- Declaration = creating a variable with a keyword.
- Initialization = giving a variable its first value.
- Reassignment = giving an existing variable a new value.
- Redeclaration = declaring the same variable again in the same scope.
- Scope = the part of the program where a variable is accessible.
- Block = code grouped between curly braces.
- Hoisting = JavaScript processes declarations before executing their surrounding code.
5. Understand Scope with a Practical Example
Scope decides where we can access a variable. This is an important difference between var, let and const.
5.1 var is function-scoped
A variable declared with var inside an if block remains available inside its surrounding function.
Example 6: Access a var variable outside an if block
function showStudentResult() {
if (true) {
var studentName = "Priya";
}
console.log(studentName);
}
showStudentResult();
Expected output
Priya
The variable belongs to the surrounding function. The if block does not limit its scope.
5.2 let and const are block-scoped
A variable declared inside a block stays inside that block. Code outside cannot access it.
Example 7: Keep a let variable inside an if block
function showStudentResult() {
if (true) {
let studentName = "Priya";
console.log(studentName);
}
}
showStudentResult();
Expected output
Priya
The variable is used inside its block. We do not access it outside.
Animation 02 · Scope boundaries
Where can the variable be accessed?
Compare the function boundary with the smaller block boundary.
The animation compares the wider function scope with the smaller block scope.
6. What Is Hoisting in JavaScript?
Hoisting = JavaScript processes declarations before running the code in their scope.
However, the three declarations behave differently. Understanding this helps prevent confusing errors.
6.1 Hoisting with var
A var declaration is hoisted and initialized with undefined. So reading it before its assignment does not throw a reference error.
Example 8: Read a var variable before its assignment
console.log(studentName);
var studentName = "Priya";
console.log(studentName);
Expected output
undefined Priya
JavaScript processes the declaration first. The assignment still happens at its original line.
6.2 Hoisting with let and const
let and const are also hoisted. But they are not initialized before their declaration.
Accessing them too early causes a ReferenceError. The period before declaration is called the Temporal Dead Zone.
Temporal Dead Zone (TDZ) = the time before a let or const declaration becomes usable.
Example 9: Accessing let before declaration
console.log(studentName);
let studentName = "Priya";
Expected result
ReferenceError: Cannot access 'studentName' before initialization
Animation 03 · Temporal Dead Zone
When does a let variable become available?
Follow the declaration from the start of its scope to initialization.
The timeline shows why let and const cannot be accessed before initialization.
Remember: Declare variables before using them. This keeps your code clear and avoids TDZ errors.
7. Can We Change an Object Declared with const?
Yes. This is a common JavaScript interview question.
const prevents reassignment of the variable binding. It does not freeze the object itself.
We can update an object's properties. We cannot assign a completely different object to the same variable.
Example 10: Update a student object declared with const
const student = {
name: "Priya",
marks: 85
};
student.marks = 90;
console.log(student.name);
console.log(student.marks);
Expected output
Priya 90
The object remains the same object. Only its marks property changes.
Example 11: Reassigning a const variable
const student = {
name: "Priya"
};
student = {
name: "Arjun"
};
Expected result
TypeError: Assignment to constant variable.
Important: const does not make nested objects immutable. Use tools such as Object.freeze() when shallow immutability is needed. Remember that Object.freeze() is shallow by default.
8. A Real Student Result Example Using All Three Keywords
Now let's combine the concepts in one small program. We will store a student's details and calculate the result.
We use const for the fixed passing marks. We use let for values that may change. This example also shows an older var declaration.
Example 12: Calculate a student's result
const PASS_MARKS = 40;
let studentName = "Priya";
let marks = 85;
var result = "Not calculated";
if (marks >= PASS_MARKS) {
result = "Pass";
} else {
result = "Fail";
}
console.log("Student:", studentName);
console.log("Marks:", marks);
console.log("Passing marks:", PASS_MARKS);
console.log("Result:", result);
Expected output
Student: Priya Marks: 85 Passing marks: 40 Result: Pass
What happens in this program?
PASS_MARKSstores the fixed passing score.studentNamestores the student's name.marksstores the student's current marks.- The condition checks whether the marks meet the passing score.
resultstores the calculated result.- The console prints all the student details.
This example uses all three declarations for learning. In modern code, prefer const and let.
9. Common Mistakes and Best Practices
Mistake 1: Using var for every variable
Wrong approach: Declaring every value with var can create scope surprises.
Better approach: Use const or let in modern JavaScript.
Mistake 2: Reassigning a const variable
Wrong approach: Assigning a new value to a const variable causes a TypeError.
Better approach: Use let when the variable needs reassignment.
Mistake 3: Declaring let or const twice in one scope
Wrong approach: Declaring the same name twice with let or const causes a SyntaxError.
Incorrect example
let marks = 85;
let marks = 90;
Better approach: Declare once, then reassign when needed.
Correct example
let marks = 85;
marks = 90;
console.log(marks);
Expected output
90
Mistake 4: Declaring const without a value
Wrong approach: A const declaration must have an initial value.
Incorrect example
const PASS_MARKS;
Better approach: Assign the value during declaration.
Correct example
const PASS_MARKS = 40;
Mistake 5: Assuming const freezes an object
Wrong approach: Expecting every object property to stay unchanged.
Better approach: Remember that const prevents reassignment, not property updates.
Best practices to follow
- Prefer
constwhen reassignment is not needed. - Use
letwhen a value must change. - Avoid
varin new JavaScript code. - Choose clear names such as
studentNameandtotalMarks. - Declare variables close to where you use them.
- Do not access
letorconstbefore declaration. - Keep variables inside the smallest useful scope.
10. How This Topic Comes Up in Interviews
Question 1: What is the difference between var, let and const?
What the interviewer wants: They want to check your understanding of scope and reassignment.
Strong answer: "var is function-scoped and allows redeclaration. let and const are block-scoped. let allows reassignment, but const does not. I prefer const by default and use let when a value must change."
Question 2: Can we change an object declared with const?
What the interviewer wants: They want to know if you understand object references.
Strong answer: "Yes, we can update an object's properties. const prevents assigning a new object to the variable. It does not freeze the object's contents."
Question 3: What is hoisting?
What the interviewer wants: They want to check how declarations behave before execution.
Strong answer: "JavaScript processes declarations before executing their surrounding code. A var variable is initialized as undefined. let and const remain uninitialized until their declaration. Accessing them early causes a ReferenceError."
Question 4: What is the Temporal Dead Zone?
Strong answer: "The Temporal Dead Zone is the time between entering a scope and initializing a let or const variable. We cannot access that variable during this period."
Question 5: Why should we avoid var in modern JavaScript?
Strong answer: "var is function-scoped and allows redeclaration. This can create unexpected behavior in larger programs. let and const provide block scope and clearer declaration rules."
What interviewers expect at different levels
- Beginner: Explain declaration, reassignment and basic differences.
- Intermediate: Explain block scope, function scope and hoisting.
- Senior: Explain TDZ, closures, loop behavior and object references.
- Architect: Explain why predictable scope and limited mutation improve maintainability.
11. Hands-On Practice
Beginner exercise: Store student details
Create variables for a student's name, age and marks. Use const for values that should not be reassigned. Print all three values.
Expected result: The console should show all three student details.
Intermediate exercise: Update exam marks
Create a let variable named marks with an initial value of 65. Update it to 80. Print both values at the correct times.
Expected result: The output should show 65 first and 80 next.
Advanced exercise: Understand block scope
Declare one variable with var and another with let inside an if block. Try accessing both outside that block, but keep the code inside a function.
Hint: The var variable remains available inside the function. The let variable is not available outside its block.
Challenge: Predict the output
Read this code carefully. Predict its output before running it.
var studentName = "Priya";
if (true) {
var studentName = "Arjun";
let marks = 90;
}
console.log(studentName);
console.log(marks);
Think about: Which variable is available outside the block? What happens when JavaScript reads marks?
Expected result
Arjun ReferenceError: marks is not defined
12. Frequently Asked Questions
Can we use var, let and const in the same program?
Yes. JavaScript supports all three declarations. However, prefer let and const for new code.
Can let be declared without an initial value?
Yes. You can declare let first and assign its value later. Until assignment, its value is undefined.
Can const be declared without an initial value?
No. A const declaration must receive a value immediately.
Which declaration should beginners use?
Start with const. Change it to let only when reassignment is needed.
Is var still supported in JavaScript?
Yes. Modern JavaScript still supports var. Existing applications may contain it.
Does const make an array immutable?
No. You can change array elements and use methods such as push. You cannot reassign the array variable itself.
13. Next Steps and Community
You now understand how JavaScript stores values using var, let and const. You also learned scope, reassignment, redeclaration, hoisting and the Temporal Dead Zone.
Try it yourself
Run each example in your browser console or a JavaScript runtime. Change the values and observe the results.
Explore further
Share your knowledge
Share your examples and questions with the Upgradix learning community. Discuss different approaches and help other learners understand JavaScript.
Upgradix by Shrash Studio – Learn Technology. Build Your Future.