FundamentalsChapter 16 of 21
Data Types
The eight types, and the line between primitives and objects.
Seven primitives and one object type
| Type | Example | For |
|---|---|---|
| string | 'hello' | text |
| number | 42, 3.14 | all ordinary numbers |
| boolean | true | yes or no |
| undefined | undefined | declared but not set |
| null | null | deliberately empty |
| bigint | 9007199254740993n | integers past the safe limit |
| symbol | Symbol('id') | unique keys |
| object | {}, [], functions | everything else |
JavaScript
console.log(typeof 'hello');
console.log(typeof 42);
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof 10n);
console.log(typeof Symbol('id'));Output
string number boolean undefined bigint symbol
The difference that matters
A primitive is a single value, copied when assigned. An object is a reference, shared when assigned. That one difference explains a lot of confusing behaviour later.
JavaScript
let a = 1;
let b = a;
b += 1;
const first = { n: 1 };
const second = first;
second.n += 1;
console.log(a, b);
console.log(first.n, second.n);Output
1 2 2 2
Copying a number gave two independent values. Copying an object gave two names for one object.
null and undefined
Both mean absent, and the distinction is about who caused it. undefined is what JavaScript uses when nothing has been set. null is what you write to say deliberately empty.
JavaScript
let notSet;
const cleared = null;
console.log(notSet);
console.log(cleared);
console.log(notSet == cleared);
console.log(notSet === cleared);Output
undefined null true false
Everything else is an object
Arrays, functions, dates and regular expressions are all objects underneath, which is why typeof is unhelpful for telling them apart.
JavaScript
console.log(typeof []);
console.log(typeof {});
console.log(typeof function () {});
console.log(Array.isArray([]));Output
object object function true
Types are attached to values
A variable has no type. The value it currently holds does, and the same name can hold a different type a line later. That flexibility is convenient and is also why careful comparison matters.
Test yourself
2 questionsWhat happens when you assign an object to a second variable?
Show the answer
Both names refer to the same object Primitives copy their value; objects copy a reference to one shared thing.
What is the intended difference between null and undefined?
Show the answer
undefined means never set; null means deliberately empty Which is why === tells them apart even though == does not.
typeof
Asking what a value is, and the three answers that mislead.