Sub topic 1
Operators, Operands, and Expressions
Prerequisites
This chapter assumes you can declare variables with let and const, know JavaScript's primitive types and objects, can write and call functions, and can run code in a browser console or Node.js.
Operators and Operands
An expression is any piece of code that produces a value. An operator combines one or more operands into a new value. In a + b, the operator is + and the operands are a and b. Unary operators such as -x and typeof x take one operand, binary operators take two, and the conditional operator ? : takes three.
Who Goes First: Precedence and Associativity
Precedence decides which operator binds first. Associativity decides how operators of the same precedence group together. Most binary operators group left to right. The ** operator groups right to left.
console.log(2 + 3 * 4); // 14
console.log((2 + 3) * 4); // 20
console.log(2 ** 3 ** 2); // 512, grouped as 2 ** 9
console.log((-2) ** 2); // 4
// -2 ** 2 is a SyntaxError: a unary operator cannot appear directly before **If you have to stop and think about the grouping, add parentheses.
How JavaScript Converts Types
Operators often convert their operands to a different type before they run. The spec defines these conversions as abstract operations:
| Operation | Purpose | Example |
|---|---|---|
| ToPrimitive | Object to primitive, using `valueOf` or `toString` | `[]` becomes `''` |
| ToNumber | Value to number | `' 42 '` becomes `42` |
| ToString | Value to string | `true` becomes `'true'` |
| ToBoolean | Value to boolean | `''` becomes `false` |
Arithmetic, Unary Operators, and the Two Faces of +
The -, *, /, %, and unary + operators always apply ToNumber to their operands. Binary + first applies ToPrimitive to both operands. If either result is a string, + concatenates. If neither is, it adds numbers.
console.log(1 + '2'); // '12'
console.log('3' - 1); // 2
console.log('3' * '4'); // 12
console.log(true + 1); // 2
console.log(+' 42 '); // 42
console.log(+''); // 0
console.log([] + {}); // '[object Object]'Truthy and Falsy Values
ToBoolean runs wherever JavaScript expects a condition, such as if, !, &&, and ||. Exactly eight values are falsy: false, 0, -0, 0n, '', null, undefined, and NaN. Every other value is truthy, including '0', 'false', [], and {}.
console.log(Boolean('0')); // true
console.log(Boolean([])); // true
console.log(!!NaN); // falseExercise
What do '5' * '2', '5' + 2, and Boolean('') evaluate to, and why?
Show answer
10, because * converts both strings to numbers. '52', because one operand of + is a string, so + concatenates. false, because the empty string is one of the eight falsy values.
Exercise
Why does 2 ** 3 ** 2 give 512 and not 64?
Show answer
The ** operator is right-associative, so the expression groups as 2 ** (3 ** 2), which is 2 ** 9.