Sub topic 1
The Eight Types: Seven Primitives and Object
Every value in JavaScript belongs to one of eight types. Seven of them are primitive types, and the eighth is object. All later topics in this tutorial depend on this split: copying, comparing, and converting values (also called coercion) each work differently for primitives and objects. This chapter lists the eight types, shows what each looks like in code, and explains what makes a value primitive.
Prerequisites
This chapter assumes you already know:
- Basic JavaScript syntax: declaring variables with
letandconst, writing functions, and using operators. - How to create and use objects and arrays.
- How to run code in a browser console or with Node.js.
You don't need any knowledge of the ECMAScript specification. When this tutorial names an internal operation such as ToNumber, it explains that operation where it first comes up.
The Seven Primitive Types
A primitive is a value that has no properties of its own and cannot be changed. The language defines exactly seven primitive types.
| Type | Example literals | What it represents |
|---|---|---|
| string | `"hi"`, `'a'`, `` `x=${1}` `` | A sequence of UTF-16 code units (text) |
| number | `42`, `3.14`, `NaN`, `Infinity` | A 64-bit IEEE 754 floating-point value |
| bigint | `10n`, `2n ** 64n` | An integer of any size |
| boolean | `true`, `false` | A logical truth value |
| undefined | `undefined` | The type's only value, meaning "no value assigned" |
| null | `null` | The type's only value, meaning "intentionally empty" |
| symbol | `Symbol("id")` | A unique identifier, often used as a property key |
Some details in this table deserve a closer look:
- number is the only numeric type for ordinary math. JavaScript has no separate integer type, so
5and5.0are the same value. Special values such asNaNand-0also have type number. A later chapter covers them. - bigint handles integers beyond the range that number can represent exactly. You write a bigint by adding
nto an integer literal. - undefined and null are each a type with a single value. Two separate "empty" types cause plenty of confusion, and a chapter later in this tutorial is devoted to them.
- symbol values are unique. Every call to
Symbol()creates a new symbol, even when you pass the same description.
const name = "Ada"; // string
const age = 36; // number
const population = 8000000000n; // bigint
const isAdmin = false; // boolean
let nickname; // undefined (declared, never assigned)
const manager = null; // null
const id = Symbol("id"); // symbol
console.log(nickname); // undefined
console.log(Symbol("id") === Symbol("id")); // false: each symbol is unique
console.log(5 === 5.0); // true: one numeric typeThe Object Type
Every value that is not a primitive is an object. An object is a collection of properties, where each property has a key (a string or a symbol) and a value. Unlike primitives, objects can be changed after they are created.
Many things that look like separate types are actually objects:
- Plain objects:
{ x: 1 } - Arrays:
[1, 2, 3] - Functions:
function () {}and() => {} - Built-ins such as
Date,RegExp,Map,Set, andError
A function is an object that can also be called. An array is an object with numeric keys and a special length property. Because they are objects, you can attach properties to them:
function greet() {
return "hello";
}
greet.callCount = 0; // functions are objects, so this works
console.log(greet.callCount); // 0
const list = [10, 20];
list.label = "scores"; // arrays are objects too
console.log(list.length); // 2: length counts only index properties
console.log(list.label); // "scores"What Makes a Primitive Primitive
Primitives have two properties that set them apart from objects.
Primitives are immutable
You cannot change a primitive value. You can only replace it with a different one. String methods such as toUpperCase return a new string and leave the original as it was.
"use strict";
const greeting = "hello";
const shouted = greeting.toUpperCase();
console.log(greeting); // "hello": unchanged
console.log(shouted); // "HELLO": a new string
let word = "cat";
word = "bat"; // reassigns the variable to a new string
console.log(word); // "bat"
try {
"cat"[0] = "b"; // a string's characters are read-only
} catch (err) {
console.log(err instanceof TypeError); // true in strict mode
}Keep two things apart: the variable and the value. With let word = "cat" you can make word point to a different string later. The string "cat" itself can never change.
Primitives have no properties of their own
"hello".length and (3.14159).toFixed(2) look like property access on a primitive. They work because JavaScript wraps the primitive in a temporary object for the duration of the lookup. The chapter on wrapper objects explains this. The two exceptions are null and undefined, which have no wrapper, so accessing any property on them throws:
console.log("hello".length); // 5
console.log((3.14159).toFixed(2)); // "3.14"
try {
null.length;
} catch (err) {
console.log(err.name); // "TypeError"
}Why the Split Matters
The line between primitive and object shows up in every later chapter:
| Behavior | Primitives | Objects |
|---|---|---|
| Can be changed after creation | No | Yes |
| Assignment copies | The value | A reference to the same object |
| `===` compares | Values | Identity (same object or not) |
| Conversion to another primitive | Direct rules | Must first go through ToPrimitive |
The last row is the key to coercion. When JavaScript needs a number or a string and gets an object, it first reduces the object to a primitive, then applies the ordinary primitive rules. Results like [] + {} giving "[object Object]" come out of this two-step process, and later chapters walk through it.
Common Mistakes
- Counting arrays or functions as separate types. Both are objects.
typeofreports"function"for functions as a convenience, but they are still objects. - Treating
nullas an object.nullis a primitive. Thetypeof null === "object"result is a historical bug, covered in the typeof chapter. - Assuming integers have their own type. Integers in ordinary code are values of type number. Only literals ending in
nare bigints. - Expecting string methods to modify in place. Methods like
replace,trim, andtoUpperCasereturn new strings. Assign the result to a variable.
Exercise
Classify each value as primitive or object, and name its type: "42", 42n, [42], null, () => 42, Symbol("42"), new Date(), NaN.
Show answer
"42" is a primitive string. 42n is a primitive bigint. [42] is an object (an array). null is a primitive of type null. () => 42 is an object (a function). Symbol("42") is a primitive symbol. new Date() is an object. NaN is a primitive of type number.
Exercise
After running let s = "data"; s.toUpperCase(); s[0] = "D"; in non-strict mode, what is the value of s, and why?
Show answer
s is still "data". toUpperCase returns a new string, and that result is thrown away because it isn't assigned to anything. The index assignment fails silently because strings are immutable. To change s, reassign it, for example s = s.toUpperCase();.
Exercise
A colleague says "JavaScript has a function type because typeof returns 'function'." How would you correct this?
Show answer
The language has eight types, and none of them is a function type. Functions are objects that can be called. typeof returns "function" for callable objects to make them easy to detect, but you can still add properties to a function like any other object.