Values, types and equality
Primitives versus objects, what typeof really tells you, and why strict equality should be your default.
Updated
Everything a JavaScript program works with is a value, and every value has a type. The difference between primitive values and objects explains most of the surprises you will meet early on: comparisons that look wrong, copies that are not really copies, and functions that change data they were never supposed to touch.
Primitives and objects
JavaScript has seven primitive types. Primitives are immutable: operations on them always produce new values instead of changing the original. Everything else is an object, including arrays, functions, dates and maps.
Copying values and references
Assigning a primitive copies the value itself. Assigning an object copies a reference to the same object, so a change made through one variable is visible through every other variable that points at it.
let a = 'strata'
let b = a
b = b.toUpperCase()
console.log(a, b) // strata STRATA
const user = { name: 'Ada' }
const alias = user
alias.name = 'Grace'
console.log(user.name) // Grace: both variables point at one objectTo copy an object, create a new one. Spread syntax copies only the top level, so nested objects and arrays are still shared. structuredClone makes a deep copy.
const original = { name: 'Ada', skills: ['math'] }
const shallow = { ...original }
const deep = structuredClone(original)
shallow.skills.push('poetry')
console.log(original.skills) // ['math', 'poetry'], the array is shared
console.log(deep.skills) // ['math'], fully independentStrict and loose equality
Strict equality (===) compares type and value without converting anything. Loose equality (==) converts both sides first, using rules that are easy to forget. Use === everywhere, and reach for Object.is in the two edge cases where it behaves differently.
NaN === NaN // false
Object.is(NaN, NaN) // true
0 === -0 // true
Object.is(0, -0) // falseType coercion in practice
Operators convert values too. The + operator concatenates as soon as either side is a string, while the other arithmetic operators convert both sides to numbers. Predict each line below, then run it to check your answers.
Checking types reliably
typeof value === 'string'works for every primitive except null.Array.isArray(value)for arrays, becausetypeof []is'object'.value === nullfor null, andvalue == nullonly when you deliberately want to match both null and undefined.value instanceof Datefor instances of a class.Number.isNaN(value)rather than the globalisNaN, which converts its argument first and returns true for'hello'.
Summary
- There are seven primitive types; everything else is an object.
- Primitives are copied by value, objects by reference.
- Use
===by default andObject.isforNaNand negative zero. - Convert input explicitly rather than relying on coercion.
Finished this lesson?
Mark it complete to track your progress across every track in the curriculum.