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;
3
4// Addition
5let sum = a + b;
6console.log(`${a} + ${b} = ${sum}`);
7
8// Subtraction
9let difference = a - b;
10console.log(`${a} - ${b} = ${difference}`);
11
12// Multiplication
13let product = a * b;
14console.log(`${a} * ${b} = ${product}`);
15
16// Division
17let quotient = a / b;
18console.log(`${a} / ${b} = ${quotient}`);
19
20// Modulus (Remainder)
21let remainder = a % b;
22console.log(`${a} % ${b} = ${remainder}`);
23
24// Exponentiation (ES6)
25let power = a ** b;
26console.log(`${a} ** ${b} = ${power}`);
27
28// Increment
29let x = 5;
30x++; // Post-increment
31console.log("After x++:", x);
32
33let y = 5;
34++y; // Pre-increment
35console.log("After ++y:", y);
36
37// Decrement
38let p = 5;
39p--; // Post-decrement
40console.log("After p--:", p);
41
42let q = 5;
43--q; // Pre-decrement
44console.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.