Data Types
Data types define what kind of value a variable holds. JavaScript has 7 primitive types (string, number, boolean, null, undefined, bigint, symbol) and reference types (objects, arrays, functions).
JavaScript needs to know whether '5' means text or a number — so it knows if '5' + 1 = '51' or 6. Understanding types prevents bugs and unexpected behavior.
Every time you create a variable or compare values. Type coercion (automatic type conversion) happens in comparisons and operations.
Use typeof to check types. Use === (strict equality) instead of == to avoid type coercion bugs. Use Array.isArray() to check for arrays since typeof [] returns 'object'.
📚Key Terms
Primitive— Immutable value types: string, number, boolean, null, undefined, bigint, symbol. Stored directly in memory.
Reference Type— Objects/Arrays stored by reference in memory. Two variables can point to the same object.
Type Coercion— JavaScript automatically converting one type to another (e.g., '5' + 1 = '51')
Strict Equality (===)— Compares both value AND type without coercion. Always prefer over ==
Code Examples
#1All 7 primitive types
// 1. String — text wrapped in quotesconst name = "Ali";const greeting = 'Hello';const template = `My name is ${name}`; // template literal// 2. Number — integers and decimals (one type!)const age = 25;const price = 9.99;const negative = -10;const infinity = Infinity;const notNumber = NaN; // "Not a Number" — result of invalid math// 3. Boolean — only true or falseconst isActive = true;const isLoggedIn = false;// 4. undefined — variable declared but NOT assignedlet unassigned;console.log(unassigned); // undefined// 5. null — INTENTIONAL absence of a valueconst data = null; // you deliberately set it to nothing// 6. BigInt — very large integers (rare, for finance/crypto)const bigNumber = 9007199254740991n; // n suffix makes it BigInt// 7. Symbol — unique identifier (rare, advanced)const id = Symbol("id");const anotherId = Symbol("id");console.log(id === anotherId); // false — Symbols are always unique
#2Type checking and coercion gotchas
// typeof checkstypeof "hello" // "string"typeof 42 // "number"typeof true // "boolean"typeof undefined // "undefined"typeof null // "object" ← Famous JS bug! Don't use typeof for nulltypeof [] // "object" ← Use Array.isArray() insteadtypeof {} // "object"typeof function(){}// "function"// Check for null specificallyconst value = null;value === null; // ✅ true — correct way// Check for arrayArray.isArray([1, 2, 3]); // ✅ trueArray.isArray("hello"); // false// ⚠️ Type coercion traps with ==0 == false // true ← BAD SURPRISE1 == "1" // true ← BAD SURPRISEnull == undefined // true ← BAD SURPRISE// ✅ Always use === (strict equality)0 === false // false ← correct behavior1 === "1" // false ← correct behavior
Practice This Concept
Open the playground, paste any example, and experiment. The best way to learn is by breaking things.
Open in Playground