Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! π
Data Types (String, Number, Boolean, null, undefined)
JavaScript has 7 primitive data types plus Object. Understanding data types is essential because operations behave differently based on type - adding two numbers gives a sum, but adding two strings concatenates them.
JavaScript Data Types
- String - Text in quotes: 'Hello', "World", `template`. Used for names, messages, HTML content
- Number - Any number: 42, 3.14, -100, Infinity, NaN. No separate integer/float types in JS
- Boolean - true or false. Used for conditions, flags, toggles
- null - Intentionally empty. You SET it to null: let user = null (no user logged in)
- undefined - Variable declared but not assigned. JS sets it automatically: let x; β undefined
- BigInt - Very large integers: 9007199254740991n. Rarely needed
- Symbol - Unique identifiers. Advanced - used in libraries/frameworks
Data Types Code
// String
const name = "Alice";
const greeting = 'Hello';
const message = `Welcome, ${name}!`; // template literal
// Number
const age = 25;
const price = 9.99;
const negative = -10;
const infinity = Infinity;
const notANumber = NaN; // 'Not a Number' - result of invalid math
// Boolean
const isLoggedIn = true;
const hasPermission = false;
// null and undefined
let user = null; // intentionally empty
let score; // undefined (not assigned)
// Checking types
console.log(typeof name); // "string"
console.log(typeof age); // "number"
console.log(typeof isLoggedIn); // "boolean"
console.log(typeof user); // "object" (JS bug - null shows as object)
console.log(typeof score); // "undefined"
console.log(typeof NaN); // "number" (another JS quirk)Tip
Tip
Use typeof to check data types when debugging: typeof myVar. Remember the quirk - typeof null returns 'object' (a known JS bug since 1995). Always check for null explicitly with value === null.
undefined/functions dropped. Always try/catch parse.
Common Mistake
Warning
Assuming empty string '', 0, and null are the same. They're all falsy but have different types: '' is a string, 0 is a number, null is intentionally empty, and undefined means never assigned. Each has distinct behavior in comparisons.
Practice Task
Note
Create variables of each type and log their typeof: (1) A string, number, and boolean. (2) A null value and an undefined variable. (3) Use typeof on each and note the results - especially typeof null and typeof NaN.
Quick Quiz
Key Takeaways
- JavaScript has 7 primitive data types plus Object.
- String - Text in quotes: 'Hello', "World", `template`. Used for names, messages, HTML content
- Number - Any number: 42, 3.14, -100, Infinity, NaN. No separate integer/float types in JS
- Boolean - true or false. Used for conditions, flags, toggles