Master arithmetic, comparison, logical, and assignment operators in JavaScript.
Arithmetic operators perform mathematical calculations on numbers:
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 3 * 7 | 21 |
/ | Division | 15 / 4 | 3.75 |
% | Modulo (remainder) | 10 % 3 | 1 |
** | Exponentiation | 2 ** 4 | 16 |
JavaScript follows the standard order of operations (PEMDAS): Parentheses, Exponentiation, Multiplication/Division, Addition/Subtraction. Use parentheses to make your intent clear.
There are also increment (++) and decrement (--) operators that add or subtract 1:
let count = 5;
count++; // count is now 6
count--; // count is back to 5Comparison operators compare two values and return a boolean (true or false):
| Operator | Meaning | Example | Result |
|---|---|---|---|
=== | Strict equal | 5 === 5 | true |
!== | Strict not equal | 5 !== '5' | true |
== | Loose equal | 5 == '5' | true |
!= | Loose not equal | 5 != '5' | false |
< | Less than | 3 < 7 | true |
> | Greater than | 10 > 20 | false |
<= | Less than or equal | 5 <= 5 | true |
>= | Greater than or equal | 8 >= 10 | false |
Always use strict equality (=== and !==). Loose equality (==) performs type coercion, which can lead to unexpected results:
0 == '' // true (both coerced to falsy)
0 === '' // false (number vs string)
null == undefined // true (special coercion rule)
null === undefined // false (different types)Logical operators combine or invert boolean expressions:
| Operator | Name | Description |
|---|---|---|
&& | AND | Returns true if both operands are truthy |
|| | OR | Returns true if at least one operand is truthy |
! | NOT | Inverts the boolean value |
true && true // true
true && false // false
true || false // true
false || false // false
!true // false
!false // trueJavaScript uses short-circuit evaluation: with &&, if the first operand is falsy, the second is never evaluated. With ||, if the first operand is truthy, the second is never evaluated.
Truthy and falsy values: In a boolean context, these values are falsy: 0, "" (empty string), null, undefined, NaN, and false. Everything else is truthy, including [], {}, and "0".
<div id="results"></div>
<script>
const a = 10;
const b = 3;
const sum = a + b; // 13
const remainder = a % b; // 1
const power = a ** 2; // 100
const isEqual = a === b; // false
const isGreater = a > b; // true
const bothTrue = isGreater && !isEqual; // true
const results = document.getElementById('results');
results.innerHTML = `
<p>${a} + ${b} = ${sum}</p>
<p>${a} % ${b} = ${remainder}</p>
<p>${a} ** 2 = ${power}</p>
<p>${a} === ${b} is ${isEqual}</p>
<p>${a} > ${b} is ${isGreater}</p>
<p>Both conditions: ${bothTrue}</p>
`;
</script>What does 5 === '5' return?