3.4 Expressions and Operators
An expression combines values, variables, and operators to compute a result. Programs use expressions to calculate, compare, join text, and update data.
Arithmetic operators
JavaScript supports common arithmetic operations:
+: addition-: subtraction*: multiplication/: division%: remainder after division**: exponentiation
console.log(21 / 4); // 5.25
console.log(22 % 3); // 1
console.log(2 ** 3); // 8Unlike Python's //, JavaScript does not have a separate floor-division operator. Use Math.floor() when you need the integer part of a division result.
console.log(Math.floor(21 / 4)); // 5Reversing a three-digit integer
Floor division and modulo are often used together to split an integer into digits.
let num = Number(prompt("Enter a 3-digit integer:"));
let a = Math.floor(num / 100);
let b = Math.floor(num / 10) % 10;
let c = num % 10;
console.log("Reversed:", c * 100 + b * 10 + a);One possible run:
Enter a 3-digit integer: 520
Reversed: 25The result is displayed as 25 because the reversed number is 025, and leading zeros are not shown when printing a number.
Compound operators
Compound assignment operators make variable updates shorter.
a += bmeansa = a + ba -= bmeansa = a - ba *= bmeansa = a * ba /= bmeansa = a / ba %= bmeansa = a % b
JavaScript also has increment and decrement:
i++; // i = i + 1
i--; // i = i - 1String concatenation
+ is not only for numbers. It can also join strings.
let s = "Hello" + "World";
s += "!";
console.log(s);Output:
HelloWorld!When one side is a string, + tends to concatenate. This is why "18" + 1 becomes "181". Convert text to a number first when you want arithmetic.