Module lessons (3/4)
Operators
Operators take one or more input values and return a new one without modifying the originals. Knowing precedence and short-circuiting rules avoids subtle errors in fallback conditions and expressions.
Mental model: strict equality and short circuit
| Family | Examples | Result | Golden rule |
|---|---|---|---|
| Arithmetics | 17 % 5, 2 ** 10 | 2, 1024 | Use ( ) when combining + with * or ** |
| Close comparison | 3 === '3', 3 !== '3' | false, true | Never use == or != in new code |
| Logical | a && b, a || b, !a | Value of the decisive operand | They stop as soon as the outcome is certain |
| Coalescence | a ?? b | b only if a is null/undefined | Respect 0, false and '' |
Progressive examples
1. Modulo %, power ** and explicit brackets
17 % 5; // 2 (resto utile per testare pari/dispari: n % 2 === 0)
2 ** 10; // 1024
2 + 3 * 4; // 14 (prodotto prima della somma)
(2 + 3) * 4; // 20 (parentesi esplicite)2. Why === always beats ==
0 == ''; // true (trappola di coercion implicita!)
0 === ''; // false (tipi diversi: number vs string)
'7' !== 7; // true3. Return value of &&, || and ??
const rawName = '';
const withOr = rawName || 'Anonymous'; // 'Anonymous' ('' è falsy)
const count = 0;
const badRetries = count || 3; // 3 (bug se 0 è un numero valido!)
const safeRetries = count ?? 3; // 0 (?? scatta solo per null/undefined)4. Compare scope and evaluation order
const isAdmin = true;
const canEdit = isAdmin && 'write-access'; // 'write-access'Guided laboratory
Arithmetic precedence
Calculates (8 + 4) raised to the power of 2 and divided by 6. The last expression must evaluate to exactly 24.
Show hint
Put (8 + 4) in parentheses before the ** operator.
Solution available after 3 attempts
Close comparison combined with AND
Write a Boolean expression that combines && with a close comparison of 7 === 7 and 5 < 10, returning true.
Show hint
Write 7 === 7 && 5 < 10;.
Solution available after 3 attempts
Default safe for 0 with ??
Implement normalizeRetries(value) that returns value if it is a valid number other than null/undefined (including 0), otherwise returns 3. Avoid the || trap!
Show hint
With value ?? 3, both 0 and other numbers remain intact.
Solution available after 3 attempts
Check for understanding
What is the result of 0 || 5 compared to 0 ?? 5?
What value is returned by 'admin' && 42 in JavaScript?