In JavaScript, var, let, and const are all used to declare variables, but they differ in scope, reassignment, redeclaration, and hoisting behavior:
1. Scope
var:Function-scoped — accessible anywhere inside the function it's declared (or globally if outside).let&const: Block-scoped — only accessible inside the{ }block (like inside anif,for, orfunction).
function test() {
if (true) {
var a = 1;
let b = 2;
const c = 3;
}
console.log(a); // 1 (works)
console.log(b); // Error: b is not defined
console.log(c); // Error: c is not defined
}
test();
2. Reassignment
let:You can change the value laterconst: You cannot change the value after first assignment (must be initialized immediately)
let x = 5;
x = 10; // OK
const y = 5;
y = 10; // Error: Assignment to constant variable
Note: For objects with const, you can modify their properties (since the reference doesn't change), but you can't reassign the whole object.
3. Redeclaration
var:You can declare the same variable multiple timeslet&const: Redeclaration causes an error
var a = 1;
var a = 2; // OK
let b = 1;
let b = 2; // Error: Identifier 'b' has already been declared
4. Hoisting
All three are "hoisted" (moved to top), but:
var: Initialized as undefined → you can access before declaration (gets undefined)let&const: Not initialized → accessing before declaration throws aReferenceError(they're in a "temporal dead zone")
console.log(a); // undefined
var a = 5;
console.log(b); // ReferenceError
let b = 5;
**Primitive types**
In JavaScript, primitive data types are the simplest kinds of values. They are not objects, and they are immutable, meaning their value cannot be changed directly
JavaScript has 7 primitive data types: string, number, boolean, null, undefined, bigint, and symbol
String: text
Number: numbers
Boolean: true/false
Null: nothing on purpose(intentional empty value)
Undefined: not yet given a value(value not assigned yet)
BigInt: very big number
Symbol: unique id
let name = "Raja";
let age = 27;
let isStudent = true;
let result = null;
let score;
let big = 12345678901234567890n;
let id = Symbol("id");
One important point: primitive values are copied by value, so if you assign one primitive variable to another, the new variable gets its own copy
== and === are different in JavaScript
==checks value only after converting types if needed===checks both value and type without converting types
5 == "5" // true
5 === "5" // false
0 == false // true
0 === false // false
null == undefined // true
null === undefined // false
Top comments (0)