CodeMIRAI
0 XP

Operators

2 min read 6 runnable examples Quiz included

Arithmetic

OperatorMeaningExampleResult
+add (or join strings)7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23.5
%remainder7 % 21
**power2 ** 101024
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: -1

Increment 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 3

x++ 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 alphabetically

Always 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 ** 9
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.