JavaScript operators
JavaScript operators are symbols that are applied to execute operations on operands.
Example
In this example, we assign values to variables a, b, and c. Add them together:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Operators Example</h2>
<p id="test"></p>
<script>
let a = 5;
let b = 12;
let c = a+ b;
document.getElementById("test").innerHTML = c;
</script>
</body>
</html>
Output
JavaScript Operators Example
17
Arithmetic operators
Arithmetic operators are used to performing arithmetic calculations on numbers, whether these numbers are literals or variables.
| Arithmetic Operator | Description |
|---|---|
| + | Addition |
| – | Subtraction |
| * | Multiplication |
| / | Division |
| ++ | Increment |
| — | Decrement |
| % | Remainder – This operator returns the reminder of a division: 10 % 3 = 1 |
Examples of Arithmetic operators
Addition
var a = 10; a += 100;
document.getElementById("test1").innerHTML = a; // 200
Subtraction
var b = 30; b -= 5;
document.getElementById("test2").innerHTML = b; // 25
Multiplication
var c = 15; c *= 5;
document.getElementById("test3").innerHTML = c; // 75
Division
var d = 30; d /= 6;
document.getElementById("test4").innerHTML = d; // 5
Remainder
var e = 10; e %= 3;
document.getElementById("test5").innerHTML = e; // 1
Assignment operators
Assignment operators assign a value to a JavaScript variable. The most commonly used operator is the equal operator = which assigns the value of its right operand to its left operand.
| Operator | Example | It’s the same as |
|---|---|---|
| = | a = b | a = b |
| += | a += b | a = a + b |
| -= | a -= b | a = a – b |
| *= | a *= b | a = a * b |
| /= | a /= b | a = a / b |
| %= | a %= b | a = a % b |
Comparison operators
Use comparison operators to determine if a variable or value is equal or different when compared to another.
| Operator | Description |
|---|---|
| == | Equal to |
| === | Exactly the same value and type |
| != | Not equal |
| !== | Not the exact same value or type |
| > | Greater than |
| >= | Greater than or equal to |
| < | Less than |
| <= | Less than or equal to |
| ? | Ternary operator |
Example
let x = 6;
document.getElementById("test").innerHTML = (x >= 9);// false
Logical operators
Logical operators are used to testing for either true or false.
| Operator | Description |
|---|---|
| && | And |
| || | Or |
| ! | Not |
Example
let x = 5;
let y = 4;
document.getElementById("demo").innerHTML =
(x < 10 && y > 1) + "<br>" +
(x < 10 && y < 1); // true false