JavaScript Arithmetic Operators
What Are Arithmetic Operators?
Arithmetic operators in JavaScript are used to perform mathematical calculations on numbers. They work with both integer and floating-point values.
List of Arithmetic Operators
Operator | Name | Description | Example | Output |
---|---|---|---|---|
+ | Addition | Adds two operands | 5 + 3 | 8 |
- | Subtraction | Subtracts right operand from left | 10 - 4 | 6 |
* | Multiplication | Multiplies two operands | 2 * 6 | 12 |
/ | Division | Divides left operand by right | 12 / 4 | 3 |
% | Modulus | Returns remainder of division | 10 % 3 | 1 |
** | Exponentiation | Raises left operand to the power of right | 2 ** 3 | 8 |
++ | Increment | Increases value by one (prefix/postfix) | ++a or a++ | a+1 |
-- | Decrement | Decreases value by one (prefix/postfix) | --a or a-- | a-1 |
1. Addition (+)
let x = 5;
let y = 3;
console.log(x + y); // Output: 8
2. Subtraction (-)
let a = 10;
let b = 6;
console.log(a - b); // Output: 4
3. Multiplication (*)
let p = 7;
let q = 4;
console.log(p * q); // Output: 28
4. Division (/)
let result = 20 / 5;
console.log(result); // Output: 4
5. Modulus (%)
let mod = 10 % 4;
console.log(mod); // Output: 2
6. Exponentiation (**)
let power = 2 ** 3;
console.log(power); // Output: 8
7. Increment (++)
let num = 5;
console.log(++num); // Output: 6 (increments first, then returns)
Postfix
let num2 = 5;
console.log(num2++); // Output: 5 (returns first, then increments)
console.log(num2); // Output: 6
8. Decrement (--)
Prefix
let count = 3;
console.log(--count); // Output: 2
Postfix
let count2 = 3;
console.log(count2--); // Output: 3
console.log(count2); // Output: 2
Arithmetic with Strings
console.log("10" + 5); // Output: "105" (string concatenation)
console.log("10"- 2); // Output: 8 (string converted to number)
The + operator behaves differently if one operand is a string. It performs concatenation instead of addition.
Recap
Operation | Symbol | Example | Output |
---|---|---|---|
Add | + | 4 + 2 | 6 |
Subtract | - | 5 - 3 | 2 |
Multiply | * | 3 * 3 | 9 |
Divide | / | 10 / 2 | 5 |
Remainder | % | 9 % 4 | 1 |
Power | ** | 2 ** 3 | 8 |
Increment | ++ | ++a | a+1 |
Decrement | -- | --a | a-1 |