Careeroza
Arithmetic & Assignment
Arithmetic Operators
Example
const a = 17, b = 5;
console.log(a + b, a - b, a * b);
console.log(a / b); // division is always floating point
console.log(a % b); // remainder
console.log(2 ** 10); // exponent
let n = 5;
n++; // increment
console.log(n);Output
22 12 85 3.4 2 1024 6
Assignment Operators
Example
let total = 100;
total += 50; // total = total + 50
total -= 20;
total *= 2;
total /= 4;
console.log(total);
let name = "Asha";
name += " Rao";
console.log(name);Output
65 Asha Rao
Floating-point Precision
Example
Numbers are 64-bit floating point, so some decimals are not exact:
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
console.log((0.1 + 0.2).toFixed(2));
console.log(Math.round((0.1 + 0.2) * 100) / 100);Output
0.30000000000000004 false 0.30 0.3
Tip: For money, calculate in the smallest unit (paise, cents) as integers.