var
Function-scoped, allows redeclaration, hoisted with undefined.
Variables are used to store data values in memory so they can be reused and manipulated later in a program.
JavaScript provides three ways to declare variables:
var (old, function-scoped)let (modern, block-scoped)const (block-scoped, constant reference)var
Function-scoped, allows redeclaration, hoisted with undefined.
let
Block-scoped, cannot be redeclared, safer alternative to var.
const
Block-scoped, cannot be reassigned after initialization.
When you write:
let x = 10;x is created10 is storedvar x = 10;var x = 20; // allowedundefinedlet x = 10;// let x = 20; ❌ errorconst x = 10;// x = 20 ❌ errorScope defines where a variable is accessible.
var){} (let, const){ let a = 10; var b = 20;}
console.log(b); // ✅ worksconsole.log(a); // ❌ errorHoisting is JavaScript’s behavior of moving declarations to the top of their scope.
console.log(x);var x = 10;Internally becomes:
var x;console.log(x); // undefinedx = 10;console.log(x); // ❌ ReferenceErrorlet x = 10;This happens due to Temporal Dead Zone (TDZ).
JavaScript has two main categories:
Primitive Types
Immutable values stored directly.
Reference Types
Stored as references (memory address).
Number
Represents integers and floating numbers.
Example: 10, 3.14
String
Sequence of characters.
Example: "Hello"
Boolean
true or false
Undefined Variable declared but not assigned
Null Intentional empty value
Symbol Unique identifier
BigInt Large integers beyond Number limit
let a = 10;let b = a;
b = 20;
console.log(a); // 10let obj1 = { name: "Sahil" };let obj2 = obj1;
obj2.name = "Kumar";
console.log(obj1.name); // KumarUsed to detect type of variable.
typeof 10; // "number"typeof "hello"; // "string"typeof true; // "boolean"typeof undefined; // "undefined"typeof null; // "object" (bug)Use let instead of var
Avoid bugs caused by function scope.
Use const by default
Only use let when reassignment is needed.
Avoid global variables
Keeps code clean and predictable.
Understand scope deeply
Prevents logical errors.