JavaScript Variables
Understand var, let, and const with real examples and best practices.
Beginner Friendly Scope Rules Interview FocusTable of Contents
What is a Variable?
A variable stores data in memory so your program can reuse and update values. JavaScript provides three keywords to declare variables: var, let, and const.
let username = "Nikhil";
const siteName = "Nikhil Learn Hub";
var score = 95;
Rules to Declare a Variable in JS
- Variable name can include letters, digits, underscore (
_), and dollar sign ($). - Variable name must not start with a digit.
- Variable names are case-sensitive (
userandUserare different). - Do not use JavaScript reserved keywords like
let,const,class,return. - Use meaningful names like
totalAmountinstead of unclear names likex. - In modern JavaScript, prefer
constby default and useletonly when reassignment is needed.
// Valid names
let userName = "Ravi";
const _count = 10;
let $price = 499;
// Invalid names
// let 2name = "A"; // Cannot start with number
// let class = "B"; // Reserved keyword
// let user-name = "C"; // Hyphen not allowed in variable name
var vs let vs const - Complete Comparison Table
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function-scoped | Block-scoped { } | Block-scoped { } |
| Hoisting | Hoisted and initialized as undefined | Hoisted but not initialized (TDZ) | Hoisted but not initialized (TDZ) |
| Re-declaration | Allowed in same scope | Not allowed | Not allowed |
| Re-assignment | Allowed | Allowed | Not allowed (for primitives) |
| Initialization required | No (defaults to undefined) | No (defaults to undefined) | Yes (must assign value) |
| Temporal Dead Zone (TDZ) | No TDZ | Has TDZ (cannot access before declaration) | Has TDZ (cannot access before declaration) |
| Window object property | Yes (attaches to window in browsers) | No | No |
| Block example | Accessible outside block | Not accessible outside block | Not accessible outside block |
| Best for | Avoid in modern JS | Reassignable variables (counters, loops) | Constants, objects, arrays, functions |
Code Examples for Each Difference
1. Scope Difference
// var = Function-scoped
function varExample() {
if (true) {
var x = 10;
}
console.log(x); // 10 (accessible outside block!)
}
// let/const = Block-scoped
function letExample() {
if (true) {
let y = 20;
const z = 30;
}
console.log(y); // ReferenceError: y is not defined
console.log(z); // ReferenceError: z is not defined
}
2. Hoisting & TDZ Difference
// var - hoisted with undefined
console.log(varVar); // undefined (not an error!)
var varVar = 5;
// let - hoisted but in TDZ
console.log(letVar); // ReferenceError: Cannot access 'letVar' before initialization
let letVar = 5;
// const - hoisted but in TDZ
console.log(constVar); // ReferenceError: Cannot access 'constVar' before initialization
const constVar = 5;
3. Re-declaration Difference
// var - allowed (dangerous!)
var name = "John";
var name = "Jane"; // No error, overwrites
console.log(name); // "Jane"
// let - NOT allowed
let age = 25;
let age = 30; // SyntaxError: Identifier 'age' has already been declared
// const - NOT allowed
const PI = 3.14;
const PI = 3.14159; // SyntaxError: Identifier 'PI' has already been declared
4. Re-assignment Difference
// var - allowed
var city = "New York";
city = "Los Angeles"; // Allowed
// let - allowed
let country = "USA";
country = "Canada"; // Allowed
// const - NOT allowed for primitives
const birthYear = 1990;
birthYear = 1991; // TypeError: Assignment to constant variable
// const WITH objects - properties CAN change
const person = { name: "Alice", age: 30 };
person.age = 31; // Allowed (modifying property)
person.city = "Paris"; // Allowed (adding property)
// person = { name: "Bob" }; // Error: Cannot reassign the object itself
// const WITH arrays - elements CAN change
const colors = ["red", "green"];
colors.push("blue"); // Allowed
colors[0] = "yellow"; // Allowed
// colors = ["black"]; // Error: Cannot reassign the array
5. Window Object Property
// In browser environment
var globalVar = "I'm attached to window";
let globalLet = "I'm NOT attached to window";
const globalConst = "I'm NOT attached to window";
console.log(window.globalVar); // "I'm attached to window"
console.log(window.globalLet); // undefined
console.log(window.globalConst); // undefined
6. Loop Behavior Difference
// var - single binding for all iterations
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Output: 3, 3, 3 (same variable shared)
// let - new binding per iteration
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 100);
}
// Output: 0, 1, 2 (separate variable each iteration)
Quick Decision Guide
// USE const by default (80% of cases)
const API_URL = "https://api.example.com";
const user = { id: 1, name: "John" };
const calculateTotal = (price, tax) => price + tax;
// USE let when you NEED to reassign
let counter = 0;
counter++;
let total = 0;
for (let i = 0; i < items.length; i++) {
total += items[i].price;
}
// AVOID var in modern JavaScript (2015+)
// Only use var if supporting ancient browsers (IE10 and below)
var oldWay = "Don't use this";
Summary: Best Practices
| Situation | Recommended | Why |
|---|---|---|
| Default choice | const | Prevents accidental reassignment, makes code predictable |
| Need to reassign | let | Block-scoped, avoids legacy var behavior |
| Loops/counters | let | Reassignment required |
| Objects/arrays | const | Can still modify contents, prevents reassignment |
| Global constants | const | Clear intent, avoids polluting window |
| Never use | var | Function-scoped, hoisting confusion, legacy behavior |
This table and these examples clearly show why const and let replaced var in modern JavaScript development (ES6+).
10 JavaScript Variables Interview Q&A
1Why prefer
let/const over var?easyAnswer: Better block scope control and fewer accidental redeclaration bugs.
2Can
const object properties change?mediumAnswer: Yes, object contents can change; only the variable binding is fixed.
3What is TDZ?medium
Answer: Temporal Dead Zone is period before
let/const declaration where access throws error.4What happens when you redeclare
let in same scope?easyAnswer: SyntaxError is thrown.
5Difference between declaration and initialization?easy
Answer: Declaration creates variable name; initialization assigns a value.
6What is shadowing in variables?medium
Answer: Inner scope variable with same name hides outer variable.
7How to declare immutable primitive?easy
Answer: Use
const for values not meant to be reassigned.8Is
var block-scoped?easyAnswer: No. It is function-scoped.
9What is implicit global variable?hard
Answer: Assignment without declaration in sloppy mode can create global variable accidentally.
10Best naming practice for constants?easy
Answer: Use descriptive uppercase snake case for true constants, e.g.
MAX_USERS.10 JavaScript Variables MCQs
1
Which keyword is block-scoped?
Explanation:
let (and const) are block-scoped.2
Which cannot be reassigned?
Explanation:
const prevents reassignment of the binding.3
var is scoped to:
Explanation:
var follows function scope.4Accessing
Accessing let before declaration gives:
Explanation: TDZ causes ReferenceError before declaration line.
5
Valid variable name is:
Explanation:
userName follows naming rules.6
Which keyword allows redeclaration in same scope?
Explanation:
var can be redeclared in the same function/global scope.7
`const user = {}` means:
Explanation: Binding is fixed, object contents may still mutate.
8
Best default variable keyword today:
Explanation: Prefer
const unless reassignment is needed.9
Shadowing means:
Explanation: Same name in inner scope hides outer scope variable.
10
Which is NOT a JavaScript declaration keyword?
Explanation:
define is not a native JS variable declaration keyword.