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.

14 min read

In short

  • Primitives compare by value, objects by reference
  • typeof null is 'object'; use Array.isArray for arrays
  • Use ===; x == null is 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:

TypeExamplesNotes
undefinedundefined"nothing was assigned"
nullnull"deliberately empty"
booleantrue, false
number42, 3.14, NaN, Infinity, -0one 64-bit floating point type for everything
bigint42n, 2n ** 64nwhole numbers of any size
string'hi', `hi ${name}`immutable, UTF-16
symbolSymbol('id')unique keys
object{}, [], functions, dates, maps, class instanceseverything 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.

▶ Try
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:

▶ Try
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 null is 'object'. It's a bug from the first version of JavaScript, kept for compatibility. Check for null with value === null.
  • Arrays are objects. Use Array.isArray(value). For dates use value instanceof Date, and check !Number.isNaN(date.getTime()) to reject an "Invalid Date".
  • typeof on 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:

  • undefined means nothing was assigned. The language produces it: a variable declared without a value, a missing property, a missing argument, a function with no return.
  • null means deliberately empty. Code produces it on purpose: "no manager", "no selection". JSON has null but no undefined.
▶ Try
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) gives b only when a is null or undefined.
  • a?.b (optional chaining) gives undefined instead of throwing when a is null or undefined.

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?noyesno
NaN vs NaNfalsefalsetrue
0 vs -0truetruefalse
null vs undefinedfalsetruefalse
'1' vs 1falsetruefalse
  • === compares type and value, with no conversion. Use it by default (ESLint's eqeqeq rule enforces it).
  • == converts the two sides toward a common type first (rules below). The one common, deliberate use is value == null, which is true for exactly null and undefined.
  • Object.is is like === but treats NaN as equal to itself and 0 as different from -0. React uses it to decide whether state changed. toBe in 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:

ValueNumber
'', ' '0 (blank strings are zero!)
'42', ' 42 ', '0x10', '1e3'42, 42, 16, 1000
'12px', 'abc'NaN
true, false1, 0
null0
undefinedNaN

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.
▶ Try
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:

  1. Same type? Compare like ===.
  2. null and undefined equal each other, and nothing else.
  3. A boolean is converted to a number first (true to 1). So '1' == true is true, and 'true' == true is false.
  4. Number vs string: the string becomes a number.
  5. Object vs primitive: the object becomes a primitive (ToPrimitive), then start again.
  6. BigInt vs number or string: compare the mathematical values.
▶ Try
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.

▶ Try
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).

▶ Try
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:

▶ Try
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.

▶ Try
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.1 is stored as the nearest binary fraction. Compare floats with a tolerance, Math.abs(a - b) < 1e-9, or a relative one scaled by Number.EPSILON (the gap between 1 and the next double, about 2.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 like 9007199254740993 silently becomes 9007199254740992 when JSON.parse reads it. That's why APIs send big ids as strings.
  • Division by zero gives Infinity or -Infinity, not an exception. 0 / 0 gives NaN.

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.

▶ Try
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).

▶ Try
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

▶ Try
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 gives NaN (except blank strings, which give 0).
  • parseInt and parseFloat read 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). Write map((s) => parseInt(s, 10)) or map(Number).

BigInt

bigint holds whole numbers of any size. Write it with an n suffix or BigInt(...).

▶ Try
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 bigint and number in arithmetic. Convert explicitly with BigInt(n) or Number(b). Comparisons (<, ==) across the two types do work.
  • JSON.stringify throws 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.

▶ Try
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.

▶ Try
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 / 2 is 2.5. Use Math.trunc or Math.floor when you want integer division.
  • No operator overloading. == can't be customised, and objects never compare by value. Records, structs and Equals don't exist. You compare fields yourself.
  • TypeScript types are erased. const age = form.age as number converts nothing. The value is still the string '42', and age + 1 is '421'. Parse at the boundary (Number(...) plus a check, or a schema library like Zod) and trust the types after that.
  • TypeScript's number includes NaN, Infinity and -0, and strictNullChecks only helps if the data really matches the types. Data from JSON.parse and fetch comes in as any or an assertion.
  • C#'s ?? and ?. behave like JavaScript's. C# has no truthiness, though, and if (count) doesn't compile there. In JavaScript it compiles, and it treats 0 as false.

In real codebases

Side note
  • Lint for it: eqeqeq (allowing == null), no-implicit-coercion, and @typescript-eslint/strict-boolean-expressions (with allowNumber: false and allowString: false, it flags if (count) on numbers and strings).
  • Everything from the outside is a string: form inputs, URL params, headers, localStorage, CSV. Convert explicitly, validate with Number.isFinite or Number.isSafeInteger, and treat a blank string as "missing", never as 0. 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

  1. typeOf: a precise type label that tells null, arrays, dates and errors apart. (easy)
  2. Defaults that keep 0 and empty strings: ?? versus ||. (easy)
  3. Money in integer cents: parse, format and split amounts with no floating point drift. (medium)
  4. Parse form input without coercion bugs: strings to numbers, integers and booleans, the strict way. (medium)
  5. Compare version strings: numeric comparison, sorting and pre-release tags. (medium)
  6. 64-bit ids with BigInt: decode and build snowflake ids without losing precision. (medium)
  7. Strict deep equality: Object.is semantics, prototypes and circular references. (hard)
  8. 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