Variables & Data Types
Variables & Data Types
Section titled “Variables & Data Types”What it means
Section titled “What it means”JavaScript variables store data values. Modern JavaScript offers three ways to declare variables: var (legacy), let (block-scoped), and const (constant).
Data types include primitives (string, number, boolean, null, undefined, symbol, bigint) and objects (including arrays, functions).
Examples
Section titled “Examples”// Variable declarationslet age = 25; // mutableconst name = "Alice"; // immutablevar legacy = "old"; // function-scoped (avoid)
// Data typeslet text = "Hello"; // stringlet count = 42; // numberlet price = 19.99; // number (no separate float)let isValid = true; // booleanlet empty = null; // nulllet notDefined; // undefinedlet id = Symbol("id"); // symbollet huge = 123n; // bigint
// Objectslet user = { name: "Bob", age: 30 };let colors = ["red", "green", "blue"];Common mistake
Section titled “Common mistake”Using var instead of let/const causes scope issues:
// BAD - var has function scopefor (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100);}// Prints: 3, 3, 3
// GOOD - let has block scopefor (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100);}// Prints: 0, 1, 2Fix: Always use let or const instead of var.
Quick practice
Section titled “Quick practice”-
What’s the difference between
letandconst?Answer
`let` allows reassignment; `const` prevents reassignment (but object properties can still change). -
What does
typeof nullreturn?Answer
`"object"` (this is a known JavaScript quirk). -
Declare a constant array and add an item to it. Does this work?
Answer
Yes! `const arr = []; arr.push(1);` works because `const` prevents reassignment, not mutation.