Arithmetic Operations in JavaScript
+ - * / % **. / is float. % is remainder. ** is power. ^ is XOR.
BeginnerBasic ProgramsExample 7 of 10
arithmetic-operations.js
1let a = 10;2let b = 3;34// Addition5let sum = a + b;6console.log(`${a} + ${b} = ${sum}`);78// Subtraction9let difference = a - b;10console.log(`${a} - ${b} = ${difference}`);1112// Multiplication13let product = a * b;14console.log(`${a} * ${b} = ${product}`);1516// Division17let quotient = a / b;18console.log(`${a} / ${b} = ${quotient}`);1920// Modulus (Remainder)21let remainder = a % b;22console.log(`${a} % ${b} = ${remainder}`);2324// Exponentiation (ES6)25let power = a ** b;26console.log(`${a} ** ${b} = ${power}`);2728// Increment29let x = 5;30x++; // Post-increment31console.log("After x++:", x);3233let y = 5;34++y; // Pre-increment35console.log("After ++y:", y);3637// Decrement38let p = 5;39p--; // Post-decrement40console.log("After p--:", p);4142let q = 5;43--q; // Pre-decrement44console.log("After --q:", q);
Output
10 + 3 = 13 10 - 3 = 7 10 * 3 = 30 10 / 3 = 3.3333333333333335 10 % 3 = 1 10 ** 3 = 1000 After x++: 6 After ++y: 6 After p--: 4 After --q: 4
What's going on
3 / 2 is 1.5, not 1. Integer division is Math.trunc(3/2) or 3 / 2 | 0 if you like pain.
2 ** 3 is 8. 2 ^ 3 is 1. XOR. I will keep saying that.