JavaScript provides many built-in math operators that allow you to perform arithmetic operations on numeric values. Here are some of the most commonly used math operators in JavaScript:
- Addition (
+
): The addition operator is used to add two or more numeric values. For example,2 + 3
will return5
. - Subtraction (
-
): The subtraction operator is used to subtract one numeric value from another. For example,5 - 2
will return3
. - Multiplication (
*
): The multiplication operator is used to multiply two or more numeric values. For example,2 * 3
will return6
. - Division (
/
): The division operator is used to divide one numeric value by another. For example,6 / 2
will return3
. - Modulus (
%
): The modulus operator is used to return the remainder of a division operation. For example,5 % 2
will return1
. - Increment (
++
): The increment operator is used to increase a numeric value by 1. For example,let x = 2; x++;
will set the value ofx
to3
. - Decrement (
--
): The decrement operator is used to decrease a numeric value by 1. For example,let x = 3; x--;
will set the value ofx
to2
.
JavaScript Math operators example
Simple example code with math operators to perform a basic calculation:
<!DOCTYPE html>
<html>
<body>
<script>
let x = 10;
let y = 5;
let addition = x + y;
console.log(`The result of x + y is: ${addition}`);
let subtraction = x - y;
console.log(`The result of x - y is: ${subtraction}`);
let multiplication = x * y;
console.log(`The result of x * y is: ${multiplication}`);
let division = x / y;
console.log(`The result of x / y is: ${division}`);
let modulus = x % y;
console.log(`The result of x % y is: ${modulus}`);
let increment = ++x;
console.log(`The result of ++x is: ${increment}`);
let decrement = --y;
console.log(`The result of --y is: ${decrement}`);
</script>
</body>
</html>
Output:
This table provides a clear and overview of each operator’s purpose, a brief example of how it’s used, and the result that is returned.
Operator | Description | Example |
---|---|---|
+ | Addition | 2 + 3 returns 5 |
- | Subtraction | 5 - 2 returns 3 |
* | Multiplication | 2 * 3 returns 6 |
/ | Division | 6 / 2 returns 3 |
% | Modulus (remainder) | 5 % 2 returns 1 |
++ | Increment (add 1) | let x = 2; x++; sets x to 3 |
-- | Decrement (subtract 1) | let x = 3; x--; sets x to 2 |
Do comment if you have any doubts or suggestions on this JS operator topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version