JavaScript Variables
In JavaScript, variables are like containers that store information — such as numbers, text, or any kind of data.
They let your program store, use, and update values dynamically.
Example:
let name = "Ajay";
const age = 25;
var city = "Lucknow";
Types of Variables in JavaScript
Variables are declared using three keywords — var
, let
, and const
.
Each behaves differently in terms of scope, redeclaration, and reassignment.
1. var
- Introduced in early versions of JavaScript.
- Function-scoped or globally scoped.
- Can be redeclared and reassigned.
- Is hoisted, meaning it’s moved to the top of its scope during execution.
- Can cause unexpected bugs due to its loose scoping behavior.
Example:
var x = 10;
var x = 20; // Redeclaration allowed
x = 30; // Reassignment allowed
console.log(x); // 30
2. let
- Introduced in ES6 (2015).
- Block-scoped (only accessible within
{ }
where it’s declared). - Can be reassigned, but not redeclared in the same scope.
- Not hoisted in a usable way (accessing before declaration causes an error).
Example:
let y = 15;
y = 25; // Reassignment allowed
// let y = 35; Error: Cannot redeclare 'y'
console.log(y); // 25
3. const
- Also introduced in ES6.
- Block-scoped, just like
let
. - Must be initialized immediately.
- Cannot be reassigned or redeclared.
- Note: If the variable holds an object or array, the reference is fixed, but the contents can still change.
Example:
const z = 100;
// z = 200; Error: Assignment to constant variable
const obj = { a: 1 };
obj.a = 2; // Allowed — property change, not reassignment
console.log(obj.a); // 2
Comparison of var, let, and const
Feature | var | let | const |
---|---|---|---|
Scope | Function or global scope | Block scope | Block scope |
Reassignment | Allowed | Allowed | Not allowed |
Redeclaration | Allowed in same scope | Not allowed in same scope | Not allowed in same scope |
Initialization | Optional (defaults to undefined) | Optional | Required at declaration |
Hoisting | Hoisted, initialized as undefined | Hoisted, not initialized (TDZ) | Hoisted, not initialized (TDZ) |
Use Case | Legacy code, loose scoping | Reassignable variables, loops | Constants, immutable references |