JavaScript Variables

Understand var, let, and const with real examples and best practices.

Beginner Friendly Scope Rules Interview Focus

Table 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 (user and User are different).
  • Do not use JavaScript reserved keywords like let, const, class, return.
  • Use meaningful names like totalAmount instead of unclear names like x.
  • In modern JavaScript, prefer const by default and use let only 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
ScopeFunction-scopedBlock-scoped { }Block-scoped { }
HoistingHoisted and initialized as undefinedHoisted but not initialized (TDZ)Hoisted but not initialized (TDZ)
Re-declarationAllowed in same scopeNot allowedNot allowed
Re-assignmentAllowedAllowedNot allowed (for primitives)
Initialization requiredNo (defaults to undefined)No (defaults to undefined)Yes (must assign value)
Temporal Dead Zone (TDZ)No TDZHas TDZ (cannot access before declaration)Has TDZ (cannot access before declaration)
Window object propertyYes (attaches to window in browsers)NoNo
Block exampleAccessible outside blockNot accessible outside blockNot accessible outside block
Best forAvoid in modern JSReassignable 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 choiceconstPrevents accidental reassignment, makes code predictable
Need to reassignletBlock-scoped, avoids legacy var behavior
Loops/countersletReassignment required
Objects/arraysconstCan still modify contents, prevents reassignment
Global constantsconstClear intent, avoids polluting window
Never usevarFunction-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?easy
Answer: Better block scope control and fewer accidental redeclaration bugs.
2Can const object properties change?medium
Answer: 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?easy
Answer: 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?easy
Answer: 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?

Avar
Blet
Cfunction
Dnone
Explanation: let (and const) are block-scoped.
2

Which cannot be reassigned?

Avar
Blet
Cconst
Dall
Explanation: const prevents reassignment of the binding.
3

var is scoped to:

ABlock
BFunction
CClass only
DLoop only
Explanation: var follows function scope.
4

Accessing let before declaration gives:

Aundefined
Bnull
CReferenceError
D0
Explanation: TDZ causes ReferenceError before declaration line.
5

Valid variable name is:

A2value
Buser-name
CuserName
Dlet
Explanation: userName follows naming rules.
6

Which keyword allows redeclaration in same scope?

Aconst
Blet
Cvar
Dnone
Explanation: var can be redeclared in the same function/global scope.
7

`const user = {}` means:

AObject cannot change
BReference cannot be reassigned
CProperties are readonly automatically
DObject is frozen
Explanation: Binding is fixed, object contents may still mutate.
8

Best default variable keyword today:

Avar
Bconst
Cglobal
Dstatic
Explanation: Prefer const unless reassignment is needed.
9

Shadowing means:

ADeleting variable
BInner variable hides outer variable
CCopying variable
DHoisting variable
Explanation: Same name in inner scope hides outer scope variable.
10

Which is NOT a JavaScript declaration keyword?

Avar
Blet
Cconst
Ddefine
Explanation: define is not a native JS variable declaration keyword.