Variables and Types
~320 words ยท 2 min read
Three ways to declare a variable
JavaScript gives you let, const, and the legacy var:
let score = 0; // reassignable
const maxPlayers = 4; // cannot be reassigned
var legacy = "avoid"; // function-scoped โ avoid in modern JS
Default to const. Switch to let only when you need to reassign. Never use var.
Primitive types
JavaScript has 7 primitive types:
- string โ text:
"hello" - number โ integers and floats:
42,3.14 - boolean โ
true/false - null โ intentionally empty
- undefined โ not yet assigned
- symbol โ unique identifiers
- bigint โ large integers:
9007199254740991n
Type coercion
JavaScript silently converts between types, which can surprise you:
"5" + 3 // "53" (string concatenation)
"5" - 3 // 2 (numeric subtraction)
0 == "" // true (loose equality coerces)
0 === "" // false (strict equality does not coerce)
Always use === (strict equality) to avoid hidden type coercion bugs.
Checking types
typeof "hello" // "string"
typeof 42 // "number"
typeof undefined // "undefined"
typeof null // "object" (historical bug โ use === null)