← JavaScript

Basic · 1 of 12 · 12 min read

Primitive values

The seven primitive types, what immutability actually means for them, and why copying a primitive behaves differently from copying an object.

  • Primitives
  • Numbers

Every value in JavaScript is either a primitive or an object. There is no third category. That one split explains copying, equality and mutation, so it is worth getting exactly right before anything else.

The seven primitives

Type Example typeof
string 'ana' "string"
number 42, 1.5, NaN, Infinity "number"
boolean true "boolean"
undefined undefined "undefined"
null null "object" ← the famous bug
symbol Symbol('id') "symbol"
bigint 9007199254740993n "bigint"
console.log(typeof 'ana');        // "string"
console.log(typeof 42);           // "number"
console.log(typeof true);         // "boolean"
console.log(typeof undefined);    // "undefined"
console.log(typeof Symbol('id')); // "symbol"
console.log(typeof 10n);          // "bigint"

console.log(typeof null);         // "object"  ← not "null"
console.log(typeof []);           // "object"  — an array is an object
console.log(typeof function () {}); // "function" — a special case of object

typeof null returning "object" is a bug from the first JavaScript engine, where the type tag reserved for objects was also used for null. It was never fixed because too much code depends on it. To test for null, compare directly:

const value = null;

console.log(typeof value === 'object'); // true  — useless, arrays and {} pass too
console.log(value === null);            // true  — this is the check
console.log(value == null);             // true  — null OR undefined, the idiomatic "either"

Immutable means the value, not the variable

A primitive can never be altered. Every string or number “operation” produces a new value and leaves the original alone:

let name = 'gabriel';

name.toUpperCase();      // produces "GABRIEL"…
console.log(name);       // "gabriel" — …and it was discarded

name = name.toUpperCase(); // reassigning the variable is a different thing
console.log(name);         // "GABRIEL"

Index assignment on a string looks like it should work and does nothing — it throws in module code, which is always strict:

'use strict';
const s = 'hello';
// s[0] = 'H';     // TypeError: Cannot assign to read only property '0'
console.log(s.replace('h', 'H')); // "Hello" — a new string
console.log(s);                   // "hello" — the original

Compare with an object, which is mutable even when held by a const:

const user = { name: 'Ana' };
user.name = 'Beto';     // allowed — the object is mutable
console.log(user.name); // "Beto"
// user = {};           // TypeError — `const` blocks rebinding, not mutation

Copying: by value or by reference

This is the distinction interviews actually test.

// Primitive — `b` gets its own copy
let a = 10;
let b = a;
b = 20;
console.log(a, b); // 10 20

// Object — `d` gets the same reference
const c = { n: 10 };
const d = c;
d.n = 20;
console.log(c.n, d.n); // 20 20  ← one object, two names

The same rule governs what happens when you pass a value into a function:

function bumpPrimitive(n) {
  n += 1;             // reassigns the local copy
}
function bumpObject(o) {
  o.n += 1;           // mutates the shared object
}
function replaceObject(o) {
  o = { n: 99 };      // reassigns the local copy of the reference
}

let n = 1;
const o = { n: 1 };

bumpPrimitive(n);
bumpObject(o);
replaceObject(o);

console.log(n, o.n); // 1 2

bumpObject changed the caller’s object; replaceObject did not, because assigning to the parameter only repoints the local name.

const x = … prevents Mutating the value
primitive reassigning x impossible — immutable
object reassigning x allowed, unless frozen

Equality follows the same split

Primitives compare by value, objects by identity:

console.log('ana' === 'ana');       // true  — same value
console.log(42 === 42);             // true

console.log([1] === [1]);           // false — two different arrays
console.log({ a: 1 } === { a: 1 }); // false

const x = { a: 1 };
console.log(x === x);               // true  — the same object

Two values worth knowing because they break the usual rules:

console.log(NaN === NaN);           // false — the only value not equal to itself
console.log(Number.isNaN(NaN));     // true  — the real check

console.log(0 === -0);              // true
console.log(Object.is(0, -0));      // false — Object.is distinguishes them
console.log(Object.is(NaN, NaN));   // true  — and treats NaN as equal to itself

Numbers are doubles

There is one number type, and it is a 64-bit float. Integers above 2^53 and most decimals are approximations:

console.log(0.1 + 0.2);                    // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);            // false
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON); // true — compare with tolerance

console.log(Number.MAX_SAFE_INTEGER);      // 9007199254740991
console.log(9007199254740993);             // 9007199254740992  ← lost precision
console.log(9007199254740993n);            // 9007199254740993n — bigint keeps it

For money, work in integers — cents rather than euros — and only format at the edge.

Primitives have methods without being objects

'ana'.toUpperCase() works even though a string is not an object. The engine wraps the primitive in a temporary object, reads the method off String.prototype, and throws the wrapper away:

const s = 'ana';
console.log(s.length);         // 3
console.log(s.toUpperCase());  // "ANA"

// Which is why assigning a property silently does nothing (in sloppy mode):
// the wrapper it was set on is discarded immediately.

null and undefined have no wrapper, which is why reading anything off them throws:

// console.log(null.length);      // TypeError: Cannot read properties of null
console.log(null?.length);        // undefined — optional chaining guards it

Common mistakes

Using typeof to test for null

Mistake. if (typeof value === 'object') to mean “is it an object”. Why it fails. null passes, and so does every array. You get a branch that runs for three different kinds of value. What to do instead. value === null for null, Array.isArray(value) for arrays, and typeof value === 'object' && value !== null for “a real object”.

Expecting a method to change the string

Mistake. name.trim() on its own line and then using name. Why it fails. Primitives are immutable; the method returned a new string that was thrown away. What to do instead. Assign the result: name = name.trim().

Comparing decimals with ===

Mistake. if (total === 0.3) after adding 0.1 + 0.2. Why it fails. Neither 0.1 nor 0.2 has an exact binary representation, so the sum lands slightly above 0.3. What to do instead. Compare with a tolerance, or keep the value in integer cents and never let a fraction into the arithmetic.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

Which of these is **not** a primitive value in JavaScript?

Assigning one variable to another behaves differently depending on what kind of value is involved.

What does this log?

Code sample
let a = 10;
let b = a;
b = 20;
console.log(a);

Why does 0.1 + 0.2 === 0.3 evaluate to false?

Practise Primitives and Numbers →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.