Last 30 Days
No notifications
JavaScript has two modern variable keywords β const (default) and let (when you need to reassign). The old var has function-scope and weird hoisting; don't use it. Values come in 8 types: 7 *primitives* (string, number, boolean, null, undefined, bigint, symbol) plus *object* (which includes arrays, functions, dates, everything else).
# Variables & Types
| keyword | scope | reassign | redeclare | hoisted |
const | block | β | β | TDZ |
let | block | β | β | TDZ |
var | function | β | β | yes (undefined) β avoid |
> Rule of thumb: start with const. Switch to let only when you actually reassign.
const PI = 3.14159;
let count = 0;
count++; // ok// PI = 3; // TypeError β Assignment to constant
const makes the binding constant, not the value. The object can still mutate:
const user = { name: "alice" };
user.name = "bob"; // β
allowed β mutating contents
// user = { name: "x" }; // β reassigning the binding| type | example | notes |
string | "hi", 'hi', \hi ${n}\`` | UTF-16; backticks = template literal |
number | 42, 3.14, Infinity, NaN | 64-bit float, no separate int |
boolean | true, false | |
null | null | "intentionally no value" |
undefined | undefined | "not assigned yet" |
bigint | 9007199254740993n | for integers > 2β΅Β³ |
symbol | Symbol("id") | unique value, mostly for library authors |
| type | example |
object | {}, [], new Date(), functions⦠|
typeof "hi" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof Symbol() // "symbol"
typeof 1n // "bigint"
typeof {} // "object"
typeof [] // "object" β arrays are objects!
typeof null // "object" β legendary historical bug, can't be fixed
typeof function(){}// "function" β functions are objects, but typeof says "function"To test for an array, use Array.isArray(x). For null, use x === null.
0.1 + 0.2 // 0.30000000000000004 (IEEE-754 floats)
1 / 0 // Infinity
-1 / 0 // -Infinity
"abc" * 2 // NaN
NaN === NaN // false β NaN is the only value not equal to itself
Number.isNaN(NaN) // true β the safe way to check
Number.MAX_SAFE_INTEGER // 9007199254740991 (use BigInt past this)const a = 'single';
const b = "double";
const name = "alice";
const msg = hi ${name}, you have ${unread} messages; // template literal
const block = `line 1
line 2
line 3`; // multi-line for freeundefined β assigned by JavaScript when nothing has been assigned yet (uninitialised variable, missing object property, function with no return).null β assigned by you to mean "intentionally empty / no value".let x; // x === undefined (auto)
let y = null; // explicit "no value"({}).foo // undefined β missing property
Number("42") // 42
Number("42px") // NaN
parseInt("42px") // 42 (stops at first non-digit)
parseFloat("3.14") // 3.14String(42) // "42"
(42).toString() // "42"
Boolean(0) // false
Boolean("") // false
Boolean(null) // false
Boolean(undefined) // false
Boolean(NaN) // false
// every other value β true (these 6 are the "falsy" values)