Operators
Arithmetic
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add (or join strings) | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3.5 |
% | remainder | 7 % 2 | 1 |
** | power | 2 ** 10 | 1024 |
JavaScript
console.log(7 + 2, 7 - 2, 7 * 2, 7 / 2);
console.log(7 % 2, 2 ** 10);
console.log(Math.floor(7 / 2)); // whole-number division
console.log(-7 % 3); // the sign follows the left side: -1Increment and decrement
JavaScript
let count = 5;
count++; // add 1
count--; // subtract 1
count += 10;
count *= 2;
console.log(count);
let a = 1;
console.log(a++); // prints 1, THEN increments
console.log(++a); // increments, THEN prints 3x++ returns the value before adding; ++x returns it after. Inside larger expressions this difference matters, which is why many people only use ++ as a statement on its own.
Comparison
JavaScript
console.log(5 > 3, 5 >= 5, 5 < 3);
console.log(5 === 5, 5 === "5", 5 !== "5");
console.log("apple" < "banana"); // strings compare alphabeticallyAlways use === and !==: they compare type and value without converting.
Logical operators
JavaScript
const age = 25, member = false;
console.log(age > 18 && member); // and
console.log(age > 18 || member); // or
console.log(!member); // not&& and || short-circuit and return one of their operands, which gives handy patterns:
JavaScript
const user = { name: "Asha" };
user.name && console.log("Hello, " + user.name); // run only if truthy
const nickname = user.nickname || "friend"; // fallback
console.log(nickname);Precedence
** first, then * / %, then + -, then comparisons, then &&, then ||. When in doubt, add brackets:
JavaScript
console.log(2 + 3 * 4);
console.log((2 + 3) * 4);
console.log(2 ** 3 ** 2); // right to left: 2 ** 9Finished this lesson?Mark it complete to earn +20 XP and move your progress on.