Sub topic 1
Operators, Operands, and Expressions
Every comparison, default value, and calculation in JavaScript is built from operators. Before looking at coercion and equality rules, you need a precise vocabulary: what an operator is, what its operands are, and how an expression produces a value. This chapter sets up that vocabulary and one model that the rest of the tutorial depends on. Operands are evaluated left to right, and operators then combine the results.
Prerequisites
This chapter assumes you can already do the following:
- Declare variables with
letandconst. - Recognize JavaScript's primitive types (number, string, boolean, null, undefined, bigint, symbol) and know that objects and arrays are not primitives.
- Write and call functions.
- Run code in a browser console or with Node.js (
node file.js).
You do not need to know any coercion rules yet. Later chapters cover them.
The Vocabulary
An operator is a symbol or keyword that computes a value from one or more inputs. Examples are +, ===, &&, typeof, and ?..
An operand is one of those inputs. In price * quantity, the operator is * and the operands are price and quantity.
An expression is any piece of code that evaluates to a value. 42 is an expression. price is an expression. price * quantity is an expression made of two smaller expressions joined by an operator. Operands can themselves be expressions of any size, so expressions nest into trees.
A statement performs an action but does not produce a value you can use. if, for, let, and return start statements. You can use an expression where a statement is expected, which is called an expression statement, but you cannot use a statement where an expression is expected.
const total = 3 * 4 + 1; // the right-hand side is an expression
console.log(`Total: ${total > 10 ? 'high' : 'low'}`); // expressions are allowed inside ${}
// console.log(`${if (total > 10) { 'high' }}`); // SyntaxError: if is a statementArity: How Many Operands
Operators are grouped by arity, meaning the number of operands they take.
| Arity | Operands | Examples |
|---|---|---|
| Unary | 1 | `-x`, `+x`, `!x`, `typeof x`, `++x`, `x++`, `void x`, `delete obj.p` |
| Binary | 2 | `a + b`, `a === b`, `a && b`, `a ?? b`, `a = b`, `a in b` |
| Ternary | 3 | `cond ? a : b` (the conditional operator, the only ternary operator) |
The same symbol can have different arities. - is binary in 5 - 2 and unary in -2. + is binary in 1 + 2 and unary in +'42', where it converts its operand to a number. When you read an expression, first decide which form a symbol is being used in.
Operators Produce Values, and Some Also Change State
Every operator expression produces a value. Some also have a side effect, a change that stays after the expression finishes, such as updating a variable.
Assignment is an operator. It stores a value and also evaluates to the value it stored:
let a;
let b;
console.log(a = 5); // 5: the assignment expression evaluates to the assigned value
a = b = 10; // b = 10 runs first and evaluates to 10, then a = 10
console.log(a, b); // 10 10Increment and decrement show the difference between the value an expression produces and its side effect most clearly. Both forms add 1 to the variable. They differ in what the expression evaluates to:
let n = 5;
console.log(n++); // 5: postfix returns the old value, then increments
console.log(n); // 6
console.log(++n); // 7: prefix increments, then returns the new value
console.log(n--); // 7
console.log(n); // 6Evaluation Order: Operands First, Left to Right
Two questions decide what an expression evaluates to:
- Grouping: which operator applies to which operands. Precedence and associativity answer this. The next chapter covers them.
- Evaluation order: the order in which operand expressions run. For most binary operators JavaScript evaluates the left operand fully, then the right operand, and then applies the operator.
These two questions are independent. Multiplication binds tighter than addition, but that does not make the multiplication's operands run first. You can watch the order with a function that logs as it returns:
function trace(label, value) {
console.log('evaluating', label);
return value;
}
const result = trace('a', 2) + trace('b', 3) * trace('c', 4);
console.log(result);
// evaluating a
// evaluating b
// evaluating c
// 14The grouping is 2 + (3 * 4). The operands still run in source order: a, then b, then c. Once b and c are known, * runs. Then + runs.
Some operators do not always evaluate all of their operands:
&&,||, and??short-circuit: they skip the right operand when the left one already decides the result.cond ? a : bevaluatescond, then only one ofaorb.?.skips the rest of the chain when the value on its left isnullorundefined.
let calls = 0;
const bump = () => ++calls;
false && bump(); // bump is never called
true || bump(); // bump is never called
const pick = true ? 'yes' : bump(); // bump is never called
console.log(calls, pick); // 0 'yes'This is why user && user.name is safe when user is null. The right side never runs.
Two Operators That Are Easy to Overlook
The comma operator evaluates each operand left to right and returns the last one. It is mostly seen in for loop headers:
const x = (console.log('first'), console.log('second'), 3);
console.log(x); // 3
for (let i = 0, j = 10; i < j; i++, j--) {
// i++, j-- is a single comma expression
}The commas in let i = 0, j = 10 and in function arguments are syntax separators, not the comma operator.
The void operator evaluates its operand and returns undefined. Its main modern use is to discard a value on purpose, for example void promise to show that a promise is intentionally not awaited.
console.log(void 0); // undefined
console.log(void 'ignored'); // undefinedA Map of the Operator Families
The rest of the tutorial goes through these families one at a time:
| Family | Operators | Covered in | Column | Column |
|---|---|---|---|---|
| Arithmetic and unary | `+ - * / % ** ++ --`, unary `+ -` | Arithmetic and Unary Operators | ||
| Equality | `== != === !==` | Strict Equality, Loose Equality | ||
| Relational | `< > <= >=` | Relational Comparisons | ||
| Logical | `&& \ | \ | ! ??` | Value Selectors, Safer Defaults |
| Access | `?.` | Safe Property Access | ||
| Assignment | `= += \ | \ | = ??=` and others | Compound and Logical Assignment |
| Type inspection | `typeof instanceof in` | Inspecting Values | ||
| Bitwise | `& \ | ^ ~ << >> >>>` | Bitwise and Shift Operators |
For each operator, ask the same three questions. What does it convert its operands to? Which operands does it evaluate? What value does it return? Asking them consistently is the best way to predict results without guessing.
Exercise
Given function t(l, v) { console.log(l); return v; }, what does const r = t('x', 0) || t('y', 2) * t('z', 3); log, and what is r?
Show answer
It logs x, y, z, and r is 6. The grouping is t('x', 0) || (t('y', 2) * t('z', 3)). The left operand runs first and returns 0, which is falsy, so || evaluates its right operand. That runs y and then z in order and computes 2 * 3 = 6.
Exercise
After let k = 1; const v = k++ + ++k;, what are v and k?
Show answer
v is 4 and k is 3. The left operand k++ evaluates to 1 and sets k to 2. The right operand ++k sets k to 3 and evaluates to 3. Then 1 + 3 = 4.
Exercise
Which of these can appear inside a template literal's ${}: a ? b : c, if (a) b, (a, b), let z = 1?
Show answer
a ? b : c and (a, b) can, because both are expressions. if (a) b and let z = 1 are statements, so they are syntax errors there.