← JavaScript

Basic · 2 of 12 · 15 min read

Operators

What each operator returns rather than what it tests, why || and ?? are not interchangeable, and the precedence rules that actually catch people.

  • Operators

Most operator questions are really one question: what value does this produce? && does not return true; it returns one of its operands. Once that clicks, the rest of the behaviour stops being surprising.

Logical operators return operands

console.log(1 || 2);          // 1  — the first truthy one
console.log(0 || 2);          // 2
console.log(null || 'x');     // "x"
console.log(1 && 2);          // 2  — the last one, if none are falsy
console.log(0 && 2);          // 0  — the first falsy one
console.log('' && 'x');       // ""

console.log(typeof (1 && 2)); // "number", not "boolean"

The rule in one line each: || returns the first truthy operand, or the last one. && returns the first falsy operand, or the last one.

They short-circuit: the right-hand side is not evaluated at all when the answer is already known.

function loud(label) {
  console.log('ran', label);
  return true;
}

true || loud('a');   // nothing logged — `||` already has a truthy value
false && loud('b');  // nothing logged — `&&` already has a falsy one
false || loud('c');  // "ran c"

That is what makes the guard idiom safe:

const user = null;
console.log(user && user.name);     // null — `.name` was never evaluated
// console.log(user.name);          // TypeError

|| versus ??

?? only falls back for null and undefined. Every other value — including 0, '' and false — passes through.

const settings = { volume: 0, title: '', dark: false };

console.log(settings.volume || 50);  // 50  ← the bug: 0 is a real choice
console.log(settings.volume ?? 50);  // 0
console.log(settings.title || 'Untitled'); // "Untitled"
console.log(settings.title ?? 'Untitled'); // ""
console.log(settings.dark || true);  // true  ← always true, the option is unusable
console.log(settings.dark ?? true);  // false
Left value left || right left ?? right
undefined right right
null right right
0 right left
'' right left
false right left
NaN right left
anything truthy left left

Default to ?? for defaults. || is right when any falsy value genuinely means “missing” — an empty string for a name, for instance.

Mixing ?? with && or || without parentheses is a syntax error, deliberately, because the precedence would not be obvious:

// const x = a || b ?? c;    // SyntaxError
const x = (1 || 2) ?? 3;     // fine — say what you mean
console.log(x);              // 1

Optional chaining

?. stops the whole chain and gives undefined if the value before it is null or undefined:

const user = { profile: { name: 'Ana' } };
const empty = {};

console.log(user.profile?.name);       // "Ana"
console.log(empty.profile?.name);      // undefined — no TypeError
// console.log(empty.profile.name);    // TypeError: Cannot read properties of undefined

console.log(empty.a?.b?.c?.d);         // undefined — it short-circuits at the first gap

Three forms, and the call one is the most useful:

const obj = { list: [1, 2], greet: () => 'hi' };

console.log(obj.list?.[0]);     // 1   — index access
console.log(obj.greet?.());     // "hi" — call it only if it exists
console.log(obj.missing?.());   // undefined — not "missing is not a function"

What it does not do is protect against a property that exists but is the wrong type, and it does not work on the left of an assignment:

const o = { n: 5 };
console.log(o.n?.toUpperCase);   // undefined — `toUpperCase` is just absent on a number
// o.a?.b = 1;                   // SyntaxError: invalid assignment target

?. pairs naturally with ??:

const config = {};
console.log(config.server?.port ?? 8080); // 8080

Equality, briefly

=== compares without conversion; == converts first. Use === everywhere, with one idiomatic exception.

console.log(1 === '1', 1 == '1');     // false true
console.log(null == undefined);        // true  — the useful exception
console.log(null === undefined);       // false
console.log(NaN === NaN);              // false — nothing equals NaN
console.log(Object.is(NaN, NaN));      // true
console.log([] == false);              // true  — and this is why `==` is avoided
// The one `==` worth writing: "null or undefined", in one test
const value = undefined;
if (value == null) console.log('missing'); // catches both

Arithmetic, and the + exception

console.log(5 / 2, 5 % 2, 2 ** 10);   // 2.5 1 1024
console.log(-7 % 3);                   // -1 — the sign follows the dividend
console.log('5' - 2, '5' * 2);         // 3 10  — these convert to numbers
console.log('5' + 2);                  // "52" — `+` prefers strings

+ is the only arithmetic operator with a string meaning, so it is the only one that concatenates. Increment position matters when you use the value:

let i = 5;
console.log(i++);  // 5 — returns the old value, then increments
console.log(i);    // 6
console.log(++i);  // 7 — increments first

Assignment shorthands

let n = 10;
n += 5;  console.log(n);  // 15
n **= 2; console.log(n);  // 225

let a = null;
a ??= 'default';  console.log(a); // "default" — assigns only if null/undefined
let b = 0;
b ||= 99;         console.log(b); // 99 — assigns if falsy
let c = 1;
c &&= 5;          console.log(c); // 5  — assigns only if truthy

??= is the one to know: it is the idiomatic way to fill in a missing entry.

const counts = {};
for (const word of ['a', 'b', 'a']) {
  counts[word] ??= 0;
  counts[word] += 1;
}
console.log(counts); // { a: 2, b: 1 }

Precedence, where it actually bites

The full table is long and not worth memorising. These four are the ones that cause bugs:

console.log(2 + 3 * 4);            // 14 — `*` before `+`
console.log(true || false && false); // true — `&&` binds tighter than `||`
console.log(1 + 2 + '3');          // "33" — left to right
console.log(typeof 1 + 'x');       // "numberx" — `typeof` binds tighter than `+`
// A classic, caused by `??`'s low precedence and `+`'s higher one:
const a = null;
console.log((a ?? 0) + 1);  // 1
// console.log(a ?? 0 + 1); // also 1 here, but the intent is unreadable — parenthesise

The ternary is right-associative, which is why chains read as a sequence of else if:

const grade = (n) => (n >= 90 ? 'A' : n >= 80 ? 'B' : n >= 70 ? 'C' : 'F');
console.log(grade(85), grade(60)); // B F

Two levels is readable; four is a function with early returns.

The comma operator, so you can read it

Evaluates each expression and returns the last. Almost always a mistake outside a for header:

let x = (1, 2, 3);
console.log(x);                       // 3
for (let i = 0, j = 10; i < j; i++, j--) { /* the legitimate use */ }

Common mistakes

|| for a default where 0 or '' is valid

Mistake. const page = input.page || 1 when page 0 exists, or || 'Untitled' on an empty title the user deliberately cleared. Why it fails. Falsy is not the same as missing, so legitimate values get replaced. What to do instead. ??, which only fills in null and undefined.

Expecting ?. to catch everything

Mistake. data?.items?.map(...) on a response where items came back as a string. Why it fails. ?. guards against null and undefined, not against the wrong type — items exists, so the chain proceeds and .map is not a function. What to do instead. Validate the shape at the boundary; ?. is for absence, not for parsing.

Chaining comparisons

Mistake. if (1 < x < 10). Why it fails. It evaluates left to right: 1 < x gives a boolean, which is then coerced to 0 or 1 and compared with 10 — so the condition is always true. What to do instead. if (x > 1 && x < 10).

const x = 50;
console.log(1 < x < 10);          // true — (1 < 50) is true, true < 10 is true
console.log(x > 1 && x < 10);     // false

Check yourself

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

|| and ?? both supply a fallback, but they do not agree on what counts as missing.

What does this log?

Code sample
const a = 0 || 10;
const b = 0 ?? 10;
console.log(a, b);

What is short-circuit evaluation?

What does user?.name give you that user && user.name does not?

Practise Operators →

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.