JavaScript · Lesson 1
Values, Types and Coercion
The eight kinds of value JavaScript has, how typeof, ===, == and Object.is see them, the conversion rules behind the famous surprises, and how numbers, NaN, -0, BigInt and strings really behave.
In short
- Primitives compare by value, objects by reference
typeof nullis'object'; useArray.isArrayfor arrays- Use
===;x == nullis the one useful== +concatenates if either side is a string- Eight falsy values; use
??for defaults - Floats aren't exact: integer cents, string ids, BigInt
JavaScript is dynamically typed: variables don't have types, values do. A variable can hold a number now and a string later. When an operator gets a value of the "wrong" type, JavaScript usually doesn't throw. It converts the value (this is called coercion) and carries on. Almost every "JavaScript is weird" meme is one of a handful of conversion rules. Learn those rules once, and the weirdness turns into something you can predict.
If you're coming from C# or TypeScript, the main shift is this: the types you know are checked at compile
time, while JavaScript's types are only checked when the code runs. TypeScript's types disappear when your
code is compiled, so at runtime every value from JSON.parse, a form field or a query string is plain
JavaScript. This topic is about that runtime layer.
Every JavaScript snippet below has a ▶ Try button. Guess the output first, then run it. Like an ES module, the lab runs your code in strict mode.
The eight kinds of value
There are seven primitive types and one object type:
| Type | Examples | Notes |
|---|---|---|
undefined | undefined | "nothing was assigned" |
null | null | "deliberately empty" |
boolean | true, false | |
number | 42, 3.14, NaN, Infinity, -0 | one 64-bit floating point type for everything |
bigint | 42n, 2n ** 64n | whole numbers of any size |
string | 'hi', `hi ${name}` | immutable, UTF-16 |
symbol | Symbol('id') | unique keys |
object | {}, [], functions, dates, maps, class instances | everything else |
Primitives are values. They can't be changed, and they compare by value. Objects are references. Two variables can point at the same object, and two objects that look the same are still different objects.
let a = 'hello';
let b = a;
b += '!'; // makes a NEW string; a is untouched
console.log(a, b);
const user = { name: 'Ann' };
const sameUser = user; // copies the reference, not the object
sameUser.name = 'Bea';
console.log(user.name); // Bea: there is only one object
console.log({ id: 1 } === { id: 1 }); // false: two different objects
console.log('abc' === 'abc'); // true: primitives compare by value
Arrays, functions, dates and class instances are all objects. That matters for equality (next sections)
and for const, which stops you rebinding a variable but doesn't stop you changing the object it points to.
The Scope, Hoisting and Strict Mode topic covers const in detail.
typeof, and its famous bug
typeof returns a string naming the type of a value:
console.log(typeof undefined, typeof true, typeof 42, typeof 42n);
console.log(typeof 'hi', typeof Symbol('id'), typeof {});
console.log(typeof [], typeof new Date(), typeof /x/); // all "object"
console.log(typeof function () {}, typeof class {}); // "function": functions are callable objects
console.log(typeof null); // "object" (a bug kept since 1995)
console.log(typeof NaN); // "number": Not-a-Number is a number
Things to remember:
typeof nullis'object'. It's a bug from the first version of JavaScript, kept for compatibility. Check for null withvalue === null.- Arrays are objects. Use
Array.isArray(value). For dates usevalue instanceof Date, and check!Number.isNaN(date.getTime())to reject an "Invalid Date". typeofon a variable that was never declared returns'undefined'instead of throwing. Old code used this for feature detection:typeof window !== 'undefined'.- When you need a precise label (for logs or error messages),
Object.prototype.toString.call(value)returns'[object Array]','[object Date]','[object Null]'and so on. The typeOf exercise builds a helper on top of these.
null vs undefined
Two "no value" values is one more than most languages have. The convention:
undefinedmeans nothing was assigned. The language produces it: a variable declared without a value, a missing property, a missing argument, a function with noreturn.nullmeans deliberately empty. Code produces it on purpose: "no manager", "no selection".JSONhasnullbut noundefined.
function greet(name) {
return name;
}
const settings = { theme: null };
console.log(greet()); // missing argument
console.log(settings.fontSize); // missing property
console.log(settings.theme); // explicitly empty
console.log(JSON.stringify({ a: undefined, b: null })); // undefined properties are dropped
console.log(null == undefined, null === undefined);
Two modern operators handle both at once:
a ?? b(nullish coalescing) givesbonly whenaisnullorundefined.a?.b(optional chaining) givesundefinedinstead of throwing whenaisnullorundefined.
Default parameters (function f(x = 1)) and destructuring defaults only kick in for undefined.
Passing null keeps the null.
Three kinds of equality
=== (strict) | == (loose) | Object.is (same value) | |
|---|---|---|---|
| converts types first? | no | yes | no |
NaN vs NaN | false | false | true |
0 vs -0 | true | true | false |
null vs undefined | false | true | false |
'1' vs 1 | false | true | false |
===compares type and value, with no conversion. Use it by default (ESLint'seqeqeqrule enforces it).==converts the two sides toward a common type first (rules below). The one common, deliberate use isvalue == null, which is true for exactlynullandundefined.Object.isis like===but treatsNaNas equal to itself and0as different from-0. React uses it to decide whether state changed.toBein the lab's tests uses it too.- Objects compare by reference with all three. No operator compares objects structurally. You write that yourself (the strict deep equality exercise) or use a library.
A fourth rule, SameValueZero, is Object.is except that 0 equals -0. includes, Map and
Set use it, so [NaN].includes(NaN) is true while [NaN].indexOf(NaN) (which uses ===) is -1.
Coercion: the rules behind the memes
When an operator needs a primitive of a certain type, JavaScript converts with three internal operations.
ToPrimitive turns an object into a primitive. It calls the object's Symbol.toPrimitive method if it
has one. Otherwise it tries valueOf() and then toString() (string-flavoured contexts like template
literals try toString() first) and uses the first result that is a primitive. Plain objects give
'[object Object]'. Arrays join their items with commas: [1, 2] becomes '1,2' and [] becomes ''.
ToNumber turns a primitive into a number:
| Value | Number |
|---|---|
'', ' ' | 0 (blank strings are zero!) |
'42', ' 42 ', '0x10', '1e3' | 42, 42, 16, 1000 |
'12px', 'abc' | NaN |
true, false | 1, 0 |
null | 0 |
undefined | NaN |
ToString is mostly what you expect: String(null) is 'null', String([1, [2, 3]]) is '1,2,3'.
Now the operators:
+first converts both sides to primitives. If either is a string, it concatenates. Otherwise it adds numbers.-,*,/,%,**and unary+always convert to numbers.<,>,<=,>=compare two strings character by character (by UTF-16 code unit). Any other mix is compared as numbers.
console.log(1 + '2', '3' - 1, '3' * '4', true + 1);
console.log([] + [], [1, 2] + [3], [] + {});
console.log(+'', +' 42 ', +'4 2', +[], +{});
console.log('10' < '9', 10 < '9'); // strings compare like words, numbers like numbers
console.log(null >= 0, null > 0, null == 0);
That last line is a classic. Relational operators convert null to 0, so null >= 0 is true. But ==
has its own table, in which null only equals null and undefined, so null == 0 is false.
The == algorithm, roughly:
- Same type? Compare like
===. nullandundefinedequal each other, and nothing else.- A boolean is converted to a number first (
trueto1). So'1' == trueis true, and'true' == trueis false. - Number vs string: the string becomes a number.
- Object vs primitive: the object becomes a primitive (ToPrimitive), then start again.
- BigInt vs number or string: compare the mathematical values.
console.log('' == 0, '0' == 0, '' == '0'); // not transitive!
console.log([] == false, [0] == false, [1, 2] == '1,2');
console.log([] == ![]); // ![] is false; [] becomes '' becomes 0
You won't write code like this, but you'll read it in interviews and debug it in old code. The looseEquals exercise implements the whole algorithm, which is the fastest way to stop being surprised by it.
You can control how your own objects convert. A Money class whose toString returns '$12.50'
logs nicely in template literals. If you add valueOf, though, price + 1 quietly does arithmetic. Most
codebases avoid valueOf on domain objects for exactly that reason.
const price = {
valueOf() { return 42; },
toString() { return 'forty-two'; },
};
console.log(price + 1, price * 2); // valueOf wins for math and for +
console.log(`${price}`); // template literals ask for a string first
Truthy and falsy
if, while, !, &&, || and the ?: operator convert values to booleans. Exactly eight values are
falsy (plus one legacy browser oddity, document.all):
false, 0, -0, 0n, '', null, undefined, NaN
Everything else is truthy, including '0', 'false', ' ', [], {} and new Boolean(false).
const samples = [["'0'", '0'], ["'false'", 'false'], ["' '", ' '], ['[]', []], ['{}', {}],
['0', 0], ["''", ''], ['NaN', NaN], ['null', null]];
for (const [label, value] of samples) {
console.log(label, value ? 'truthy' : 'falsy');
}
The bug this causes in real code is || for defaults:
function connect(options) {
const retries = options.retries || 3; // bug: 0 retries becomes 3
const label = options.label ?? 'main'; // right: only null/undefined get the default
return { retries, label };
}
console.log(connect({ retries: 0, label: '' }));
|| falls back on any falsy value, so 0, '' and false (all valid settings) get replaced. Use ??
for defaults, and || only when every falsy value really means "missing". The same trap appears in
if (count) when count can be 0, and in React as {items.length && <List />}, which renders a 0.
Numbers are 64-bit floats
JavaScript has one number type: an IEEE 754 double, like C#'s double. There is no int, no
decimal, no overflow exception.
console.log(0.1 + 0.2, 0.1 + 0.2 === 0.3);
console.log((1.005).toFixed(2)); // "1.00", not "1.01"
console.log(19.99 * 100); // not 1999
console.log(2 ** 53, 2 ** 53 + 1); // past 2^53, integers get skipped
console.log(Number.MAX_SAFE_INTEGER, Number.isSafeInteger(2 ** 53));
- Decimal fractions aren't exact.
0.1is stored as the nearest binary fraction. Compare floats with a tolerance,Math.abs(a - b) < 1e-9, or a relative one scaled byNumber.EPSILON(the gap between1and the next double, about2.2e-16). - Money: store and add amounts as integer cents (minor units), and only format at the edges with
Intl.NumberFormat. For decimal maths, such as tax rates on big amounts, use a decimal library. The money in cents exercise practises this. - Integers are exact up to
2^53 - 1(Number.MAX_SAFE_INTEGER, about 9 quadrillion). Above that, not every integer can be stored. A 64-bit database id like9007199254740993silently becomes9007199254740992whenJSON.parsereads it. That's why APIs send big ids as strings. - Division by zero gives
Infinityor-Infinity, not an exception.0 / 0givesNaN.
NaN
NaN ("not a number") is what failed maths returns: Number('abc'), 0 / 0, Math.sqrt(-1). It spreads
through every calculation it touches, and it's the only value not equal to itself.
const n = Number('12px');
console.log(n, n === n, Number.isNaN(n));
console.log(isNaN('abc'), Number.isNaN('abc')); // the global isNaN converts first
console.log([NaN].includes(NaN), [NaN].indexOf(NaN));
Use Number.isNaN(x) (no conversion) rather than the global isNaN(x), which converts its argument first.
To validate user input, Number.isFinite(x) rejects NaN and both infinities in one check.
-0
Floats have a negative zero. It equals 0 with ===, but it's still there: 1 / -0 is -Infinity, and
Math.round(-0.4) gives -0. Most of the time it's harmless. It shows up when you print it (the lab's
console shows -0, but String(-0) is '0'), in sign-sensitive maths, and when Object.is is the
comparison (React state, the lab's toBe).
console.log(-0 === 0, Object.is(-0, 0), 1 / -0);
console.log(Math.round(-0.4), String(-0), JSON.stringify(-0));
parseInt, parseFloat and Number
console.log(Number('12px'), parseInt('12px'), parseFloat('3.5kg'));
console.log(Number(''), parseInt(''));
console.log(['10', '10', '10'].map(parseInt));
Number(s)converts the whole string or givesNaN(except blank strings, which give0).parseIntandparseFloatread as far as they can and ignore the rest. That's handy for'12px'and dangerous for validation. Always pass a radix:parseInt(s, 10).map(parseInt)passes the index as the radix:parseInt('10', 0),parseInt('10', 1),parseInt('10', 2). Writemap((s) => parseInt(s, 10))ormap(Number).
BigInt
bigint holds whole numbers of any size. Write it with an n suffix or BigInt(...).
const id = 9007199254740993n;
console.log(id + 1n, 2n ** 64n, 7n / 2n); // division truncates
console.log(typeof id, 1n == 1, 1n === 1);
try {
console.log(id + 1);
} catch (e) {
console.log(e.name + ': ' + e.message);
}
console.log(BigInt('123456789012345678901234567890') * 2n);
- You can't mix
bigintandnumberin arithmetic. Convert explicitly withBigInt(n)orNumber(b). Comparisons (<,==) across the two types do work. JSON.stringifythrows on BigInt. Send big integers as strings.- Use it for 64-bit ids, exact large counters and bit tricks on 64-bit values. It isn't a decimal type:
BigInt(1.5)throws.
Strings are immutable
Every string method returns a new string. Assigning to an index does nothing in sloppy mode and throws in strict mode.
const s = 'abc';
const upper = s.toUpperCase();
console.log(s, upper);
try {
s[0] = 'x';
} catch (e) {
console.log(e.name + ': ' + e.message);
}
console.log('😀'.length, [...'😀'].length); // length counts UTF-16 code units
'abc'.toUpperCase() works on a primitive because JavaScript briefly wraps it in a String object to find
the method. Never create those wrappers yourself: new String('a') === 'a' is false, and
new Boolean(false) is truthy.
Template literals (backticks) interpolate any expression with ${...} and can span lines. The
interpolated value is converted with ToString, so ${null} prints null and ${{}} prints
[object Object]. A function placed before the backtick is a tag. It receives the literal parts and
the values separately, which is how String.raw, lit-html and SQL query builders work.
const qty = 3;
const item = { name: 'Widget', price: 2.5 };
console.log(`${qty} x ${item.name} = ${(qty * item.price).toFixed(2)}`);
console.log(`missing: ${undefined}, empty: ${null}, object: ${{}}`);
console.log(String.raw`C:\new\table`);
Coming from C# or TypeScript
Side note
- No integer type.
5 / 2is2.5. UseMath.truncorMath.floorwhen you want integer division. - No operator overloading.
==can't be customised, and objects never compare by value. Records, structs andEqualsdon't exist. You compare fields yourself. - TypeScript types are erased.
const age = form.age as numberconverts nothing. The value is still the string'42', andage + 1is'421'. Parse at the boundary (Number(...)plus a check, or a schema library like Zod) and trust the types after that. - TypeScript's
numberincludesNaN,Infinityand-0, andstrictNullChecksonly helps if the data really matches the types. Data fromJSON.parseandfetchcomes in asanyor an assertion. - C#'s
??and?.behave like JavaScript's. C# has no truthiness, though, andif (count)doesn't compile there. In JavaScript it compiles, and it treats0as false.
In real codebases
Side note
- Lint for it:
eqeqeq(allowing== null),no-implicit-coercion, and@typescript-eslint/strict-boolean-expressions(withallowNumber: falseandallowString: false, it flagsif (count)on numbers and strings). - Everything from the outside is a string: form inputs, URL params, headers,
localStorage, CSV. Convert explicitly, validate withNumber.isFiniteorNumber.isSafeInteger, and treat a blank string as "missing", never as0. The form parser exercise practises this. - Defaults with
??, and??=to fill a missing property. - Money as integer minor units, formatted with
Intl.NumberFormat. Use a decimal library when you need more than add, subtract and split. - Ids as strings, and BigInt only when you really need the maths.
- Sorting:
array.sort()without a comparator sorts by string, so[10, 1, 2]becomes[1, 10, 2]and'1.10.0'sorts before'1.9.0'. Always pass a comparator:(a, b) => a - b.
The exercises
- typeOf: a precise type label that tells
null, arrays, dates and errors apart. (easy) - Defaults that keep 0 and empty strings:
??versus||. (easy) - Money in integer cents: parse, format and split amounts with no floating point drift. (medium)
- Parse form input without coercion bugs: strings to numbers, integers and booleans, the strict way. (medium)
- Compare version strings: numeric comparison, sorting and pre-release tags. (medium)
- 64-bit ids with BigInt: decode and build snowflake ids without losing precision. (medium)
- Strict deep equality:
Object.issemantics, prototypes and circular references. (hard) - looseEquals without ==: the full
==algorithm, including ToPrimitive. (hard)
Practise this lesson
In the app: a short video, 8 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app