Performing mathematical operations and calculations is a common task in programming languages. In JavaScript, there are several operators available to work with numbers.

Addition (+)

The addition operator (+) is used to add two numbers together. It can also be used for string concatenation.

const three = 1 + 2
const four = three + 1
const three = 1 + 2
three + 1 // 4
'three' + 1 // "three1"

Subtraction (-)

The subtraction operator (-) is used to subtract one number from another.

const two = 4 - 2

Division (/)

The division operator (/) is used to divide one number by another. It returns the quotient of the division.

const result = 20 / 5 //result === 4
const result = 20 / 7 //result === 2.857142857142857

If you attempt to divide by zero, JavaScript does not raise an error but returns the value Infinity (or -Infinity if the value is negative).

1 / 0 // Infinity
1 / 0 // -Infinity

Remainder (%)

The remainder operator (%) returns the remainder after dividing one number by another.

const result = 20 % 5 //result === 0
const result = 20 % 7 //result === 6

If you attempt to divide by zero, the result will always be NaN (Not a Number).

(1 % 0) // NaN
(1 % 0) // NaN

Multiplication (*)

The multiplication operator (*) is used to multiply two numbers together.

1 * 2 // 2
1 * -2 // -2

Exponentiation (**)

The exponentiation operator (**) is used to raise a number to the power of another number.

1 ** 2 // 1
2 ** 1 // 2
2 ** 2 // 4
2 ** 8 // 256
8 ** 2 // 64

The exponentiation operator ** is equivalent to using the Math.pow() function.

Math.pow(4, 2) == 4 ** 2

Increment (++)

The increment operator (++) is used to increase the value of a number. It can be used as a prefix (++x) or a postfix (x++).

let x = 0
x++ // 0
x // 1
++x // 2

Decrement (–)

The decrement operator (--) is used to decrease the value of a number. It can be used as a prefix (–x) or a postfix (x–).

let x = 0
x-- // 0
x // -1
--x // -2

Unary Negation (-)

The unary negation operator (-) returns the negation of the operand.

let x = 2 - x // -2
x // 2

Unary Plus (+)

The unary plus operator (+) tries to convert the operand to a number. If the operand is already a number, it does nothing.

let x = 2 + x // 2

x = '2' + x // "2"

x = '2a' + x // NaN

Tags: JavaScript, Arithmetic, Operators