The JavaScript Arithmetic Operators
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.
1 | const three = 1 + 2 |
1 | const three = 1 + 2 |
Subtraction (-)
The subtraction operator (-
) is used to subtract one number from another.
1 | const two = 4 - 2 |
Division (/)
The division operator (/
) is used to divide one number by another. It returns the quotient of the division.
1 | const result = 20 / 5 //result === 4 |
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 | 1 / 0 // Infinity |
Remainder (%)
The remainder operator (%
) returns the remainder after dividing one number by another.
1 | const result = 20 % 5 //result === 0 |
If you attempt to divide by zero, the result will always be NaN
(Not a Number).
1 | (1 % 0) // NaN |
Multiplication (*)
The multiplication operator (*
) is used to multiply two numbers together.
1 | 1 * 2 // 2 |
Exponentiation (**)
The exponentiation operator (**
) is used to raise a number to the power of another number.
1 | 1 ** 2 // 1 |
The exponentiation operator **
is equivalent to using the Math.pow()
function.
1 | 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++).
1 | let x = 0 |
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–).
1 | let x = 0 |
Unary Negation (-)
The unary negation operator (-
) returns the negation of the operand.
1 | let 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.
1 | let x = 2 + x // 2 |
Tags: JavaScript, Arithmetic, Operators