Arithmetic Operators
Overview
Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/).
JavaScript also provides advanced operators like Exponentiation () introduced in ES2016, and Modulo (%) which is heavily used in algorithms to find remainders (like checking if a number is even or odd).
Additionally, Increment (++) and Decrement (--) are unary operators that add or subtract one from their operand, which are fundamental in for loops.
Syntax
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)let a = 10;
let b = 3;
// Modulo returns the division remainder
console.log(a % b); // 1 (Because 10 = 3*3 + 1)
// Exponentiation (a to the power of b)
console.log(a ** b); // 1000let count = 5;
count++; // Post-increment (adds 1 after returning)
console.log(count); // 6
count--; // Post-decrement
console.log(count); // 5Common Pitfalls
- Using the addition operator (
+) with strings. If any operand is a string, JavaScript converts the other operands to strings and concatenates them instead of adding. Example:5 + '5'becomes'55', not10. - Prefix vs Postfix Increment:
let a = 5; let b = a++;setsbto 5 andato 6.let a = 5; let b = ++a;setsbto 6 andato 6.
Interview Questions
Prefix increments the value and returns the NEW value. Postfix returns the ORIGINAL value, and then increments the variable under the hood.
By using num % 2. If num % 2 === 0, the number is perfectly divisible by 2 and therefore even. If it returns 1 (or -1), it is odd.
Real-World Example
Calculating the total price of items in a shopping cart, applying a tax rate, and converting it to cents for payment processing (like Stripe requires).
const subtotal = 50.00;
const taxRate = 0.08; // 8%
const totalInDollars = subtotal + (subtotal * taxRate);
const totalInCents = totalInDollars * 100;Check Your Knowledge
Test your understanding of Arithmetic Operators with these quick questions.