Sub topic 3
&&, ||, and ! as Value Selectors
This chapter assumes you know truthy and falsy values and the difference between == and ===. Both were covered in the previous chapters.
Logical Operators Return Operands
&& and || return one of their operands, which is not always a boolean. a || b returns a if a is truthy, and otherwise returns b. a && b returns a if a is falsy, and otherwise returns b. Both stop evaluating as soon as they know the result, which is called short-circuiting. ! is the only one of the three that always returns a boolean, and !!x converts x to its boolean value.
console.log(0 || 'default'); // 'default'
console.log('a' && 'b'); // 'b'
console.log('' && 'never'); // ''
console.log(!!'text'); // trueSafer Defaults with ??
|| replaces every falsy value, including 0 and '', which are often valid data. ?? replaces only null and undefined.
console.log(0 || 10); // 10, which is probably a bug
console.log(0 ?? 10); // 0Safe Property Access with ?.
?. stops and returns undefined when the value on its left is null or undefined. It pairs well with ??.
const user = { profile: null };
console.log(user.profile?.city ?? 'Unknown'); // 'Unknown'
console.log(user.save?.()); // undefinedCompound and Logical Assignment
x += 1 is shorthand for x = x + 1. The logical forms assign only when their short-circuit condition allows it. ||= assigns when the current value is falsy, &&= assigns when it is truthy, and ??= assigns when it is nullish.
const opts = { retries: 0, name: '' };
opts.retries ||= 3; // 3
opts.name ??= 'anon'; // stays ''
console.log(opts);Inspecting Values with typeof, instanceof, and in
| Operator | Checks | Gotcha |
|---|---|---|
| `typeof x` | The type tag | `typeof null` is `'object'` |
| `x instanceof C` | Whether `C.prototype` is in the prototype chain of `x` | Fails across realms (for example, iframes), so use `Array.isArray` for arrays |
| `'k' in obj` | Whether the key exists | Returns true even when the value is `undefined` |
Bitwise Operators and BigInt
Bitwise operators convert their operands to 32-bit integers, so -1 >>> 0 is 4294967295. BigInt arithmetic requires both operands to be BigInt, and 1n + 1 throws a TypeError. Comparisons between the two types are allowed: 1n == 1 is true, 1n === 1 is false, and 2n > 1 is true.
console.log(5 & 3, 5 | 3, ~5); // 1 7 -6
console.log(7n / 2n); // 3nExercise
A config has { timeout: 0 }. What do config.timeout || 5000 and config.timeout ?? 5000 return?
Show answer
The first returns 5000, because 0 is falsy. The second returns 0, because 0 is neither null nor undefined.
Exercise
Why can 'x' in obj be true while obj.x is undefined?
Show answer
in checks whether the key exists. A property can exist and have the value undefined.