JavaScript Arithmetic

Arithmetic operators perform the everyday math of programming, from simple sums to remainders and exponents.

The basic math operators

Arithmetic operators take numeric operands and return a numeric result. The four you already know from school are addition, subtraction, multiplication, and division. JavaScript writes them with the plus, minus, asterisk, and forward slash symbols. These form the backbone of any calculation, whether you are totaling a shopping cart or scaling a value for a chart.

Core arithmetic

<!DOCTYPE html>
<html>
<body>

<h2>Core arithmetic</h2>

<script>
let x = 10;
let y = 3;

console.log(x + y); // 13  addition
console.log(x - y); // 7   subtraction
console.log(x * y); // 30  multiplication
console.log(x / y); // 3.3333333333333335  division
</script>

</body>
</html>

Remainder and exponentiation

Beyond the four basics, the remainder operator (%) returns what is left over after division, which is invaluable for tasks like checking whether a number is even. The exponentiation operator (**) raises a number to a power, so 2 ** 3 is 2 multiplied by itself three times. Both are modern, reliable parts of the language.

Remainder and power

<!DOCTYPE html>
<html>
<body>

<h2>Remainder and power</h2>

<script>
console.log(10 % 3);  // 1   remainder of 10 / 3
console.log(8 % 2);   // 0   evenly divisible, so 0
console.log(2 ** 3);  // 8   2 to the power of 3
console.log(9 ** 0.5); // 3  square root via power of 0.5

// A common use: is a number even?
let num = 7;
console.log(num % 2 === 0); // false
</script>

</body>
</html>

Increment and decrement

The increment operator (++) adds one to a variable and the decrement operator (--) subtracts one. They can appear before the variable (prefix) or after it (postfix). The difference matters when you use the value in the same expression: prefix changes the value before it is read, while postfix returns the old value first and then changes it.

  • ++ adds one to a numeric variable.
  • -- subtracts one from a numeric variable.
  • Prefix form (++x) updates first, then returns the new value.
  • Postfix form (x++) returns the current value first, then updates.
OperatorNameExampleResult
+Addition7 + 29
-Subtraction7 - 25
*Multiplication7 * 214
/Division7 / 23.5
%Remainder7 % 21
**Exponentiation7 ** 249
++Incrementlet n = 7; n++8
--Decrementlet n = 7; n--6
Note: Dividing by zero does not throw an error in JavaScript. It returns Infinity, and 0 / 0 returns NaN (Not a Number). Always guard against a zero divisor when the value could be user supplied.
Note: Decimal math is not exact because numbers are stored in binary. For example 0.1 + 0.2 gives 0.30000000000000004. When precision matters, round the result or work with integer cents instead of fractional currency.