Module lessons (3/4)
Operators
Operators are the punctuation marks of the language: they take one or more values and produce a new one. JavaScript has dozens of them; in this lesson we look at the three most common families — arithmetic, comparison, logical — and learn to read their precedence.
Arithmetic
2 + 3; // 5
10 - 4; // 6
6 * 7; // 42
20 / 4; // 5
17 % 5; // 2 ← resto della divisione (modulo)
2 ** 10; // 1024 ← elevamento a potenzaThe % operator (modulo) returns the remainder of integer division and
is extremely useful: you'll use it to check whether a number is even
(n % 2 === 0), to rotate indices, to format times.
Precedence and parentheses
As in math, * and / have higher precedence than + and -. When the
calculation is not obvious, use parentheses: they make the intent
explicit and protect you from bugs:
2 + 3 * 4; // 14 ← prima il prodotto
(2 + 3) * 4; // 20 ← prima la somma, grazie alle parentesiComparison
3 === 3; // true
3 === '3'; // false ← stesso "valore", tipi diversi
3 !== '3'; // true
5 > 3; // true
5 >= 5; // trueLogical
true && false; // false ← AND: vero solo se entrambi sono veri
true || false; // true ← OR: vero se almeno uno è vero
!true; // false ← NOT: inverteBoth && and || are short-circuit: they stop evaluating as soon as
the result is determined. This property is the basis for patterns like:
const nome = utente?.nome || 'Anonimo';
// se utente.nome è "falsy", usa 'Anonimo'Try it
Calculate the value of (8 + 4) to the power of 2, divided by 6. The last expression must return 24.
Show hint
Parentheses force the sum before the exponentiation; ** is exponentiation.
Solution available after 3 attempts
Review exercise
Write a single expression that returns `true` only if 7 is strictly equal to 7 (also by type) AND at the same time 5 is less than 10.
Show hint
Combine two comparisons with && (logical AND).
Solution available after 3 attempts