In JavaScript, arithmetic operators are used to perform mathematical operations between numeric operands. These operators are fundamental to any programming language and allow you to carry out calculations, ranging from basic to complex. Here's an overview of the arithmetic operators available in JavaScript:
-
Addition (
+
): Adds two operands.let result = 5 + 3; // result is 8
-
Subtraction (
-
): Subtracts the second operand from the first.let result = 5 - 3; // result is 2
-
Multiplication (
*
): Multiplies two operands.let result = 5 * 3; // result is 15
-
Division (
/
): Divides the first operand by the second.let result = 15 / 3; // result is 5
-
Remainder (
%
): Returns the remainder left over when one operand is divided by a second operand.let result = 5 % 3; // result is 2
-
Exponentiation (
**
): Raises the first operand to the power of the second operand.let result = 5 ** 3; // result is 125 (5*5*5)
-
Increment (
++
): Adds one to its operand. The increment operator can be used as a prefix or postfix operator.let a = 5; let b = a++; // b is 5, a is 6 after this line let c = ++a; // c is 7, a is 7 before c is assigned
-
Decrement (
--
): Subtracts one from its operand. The decrement operator can also be used as a prefix or postfix operator.let a = 5; let b = a--; // b is 5, a is 4 after this line let c = --a; // c is 3, a is 3 before c is assigned
-
Unary Negation (
-
): Returns the negation of its operand.let a = 5; let b = -a; // b is -5
-
Unary Plus (
+
): Attempts to convert the operand into a number, if it isn't already.let a = "5"; let b = +a; // b is now the number 5, not the string "5"
Special Cases
-
Addition with Strings: If one or both operands are strings, the
+
operator will concatenate the strings rather than performing arithmetic addition.let result = "Hello, " + "world!"; // result is "Hello, world!"
-
Division by Zero: Dividing a number by
0
does not throw an error in JavaScript but results inInfinity
or-Infinity
.let result = 5 / 0; // result is Infinity
-
NaN (Not a Number): Certain operations might result in
NaN
, indicating that the result is not a valid number.let result = "a" * 3; // result is NaN