JavaScript has 8 primitive data types and objects:
undefined
– A declared but uninitialized variable.null
– Intentional absence of value.boolean
– true
or false
.number
– Floating-point numbers, Infinity
, NaN
.bigint
– Large integers (1n
, 9007199254740991n
).string
– Text enclosed in quotes ('hello'
, "world"
).symbol
– Unique identifiers.object
– Collections of key-value pairs ({}
, []
, function(){}
).Type Checking
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (Legacy bug in JavaScript)
console.log(typeof true); // "boolean"
console.log(typeof 42); // "number"
console.log(typeof 9007199254740991n); // "bigint"
console.log(typeof "Hello"); // "string"
console.log(typeof Symbol("id")); // "symbol"
console.log(typeof {}); // "object" (Plain object)
console.log(typeof []); // "object" (Array is a special kind of object)
console.log(typeof function(){}); // "function" (Function is a special type of object)
console.log(typeof class {}); // "function" (Classes are syntactic sugar for functions)
console.log(typeof new Date()); // "object" (Date is a built-in object)
console.log(typeof /regex/); // "object" (RegExp is an object)
console.log(typeof Math); // "object" (Math is a built-in object)
console.log(typeof JSON); // "object" (JSON is also an object)
console.log(typeof NaN); // "number" (NaN stands for "Not-a-Number" but is still of type number)
console.log(typeof Infinity); // "number" (Infinity is a special numeric value)
console.log(typeof (() => {})); // "function" (Arrow function)
console.log(typeof new Map()); // "object" (Map is an object)
console.log(typeof new Set()); // "object" (Set is an object)
console.log(typeof new WeakMap()); // "object" (WeakMap is an object)
console.log(typeof new WeakSet()); // "object" (WeakSet is an object)
JavaScript supports three variable declarations:
var
– Function-scoped, hoisted, allows re-declaration.let
– Block-scoped, not re-declarable in the same scope.const
– Block-scoped, immutable reference.let x = 10; // Block-scoped
const PI = 3.14; // Cannot be reassigned
const obj = { a: 1 };
obj.a = 2; // Allowed (const prevents reassignment, but object properties are mutable)
var y = 20; // Function-scoped (not recommended)
Scope