Lesson

JS Arithmetic

10 min reading
Free Course

JavaScript Arithmetic: Operations, Remainders, and Precision

JavaScript arithmetic operators perform mathematical calculations on numbers, including addition (+), subtraction (-), multiplication (*), division (/), remainder (%), and exponentiation (**).

Arithmetic Operators Reference

Operator Meaning Example Result
+ Addition 8 + 3 11
- Subtraction 8 - 3 5
* Multiplication 8 * 3 24
/ Division 9 / 2 4.5
% Remainder (modulo) 9 % 2 1
** Exponentiation 2 ** 4 16

Prefix vs. Postfix Increment (++)

Both ++x and x++ add 1 to a number, yet they return different values inside larger expressions. Prefix ++x increments first and returns the new value, whereas postfix x++ returns the old value before incrementing.

let page = 1;
console.log("Postfix returns old:", page++); // 1, then page becomes 2
console.log("Prefix returns new:", ++page);  // 3

// Safe currency math using integer cents
const itemCents = 10 + 20;
const dollars = itemCents / 100;
console.log("Exact dollars:", dollars); // 0.3

Handling Floating-Point Math

JavaScript stores numbers in 64-bit binary floating-point format, so 0.1 + 0.2 evaluates to 0.30000000000000004. For money and invoices, convert amounts to integer cents before adding or multiplying, then divide by 100 at display time.

Common Mistakes to Avoid

  • Adding strings and numbers with +: "5" + 2 produces "52" because + concatenates whenever either side is a string. Convert inputs with Number(value) first.
  • Assuming / drops decimals: Unlike Java or C integer division, 5 / 2 in JavaScript returns 2.5. Use Math.trunc(5 / 2) when you need a whole integer.
  • Forgetting % sign rules: In JavaScript, -7 % 3 returns -1, matching the sign of the left dividend.

Frequently Asked Questions

What happens when I divide by zero in JavaScript?

Dividing a positive number by 0 returns Infinity, dividing a negative number by 0 returns -Infinity, and 0 / 0 returns NaN (Not a Number).

How do I calculate powers without Math.pow()?

Use the ES2016 exponentiation operator **, such as 3 ** 2 for 9 or 16 ** 0.5 for square root 4.

How can I check if an integer is even or odd?

Check the remainder after dividing by 2: num % 2 === 0 is true for even integers.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
JavaScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum