
Letβs go through Operators in JavaScript step by step.
πΉ Operators in JavaScript
π Operators are symbols that tell JavaScript to perform some operation on values (operands).
Example:
let x = 5 + 3; // + is an operator, 5 & 3 are operands
1οΈβ£ Arithmetic Operators
Used for mathematical operations.
Operator | Description | Example | Result |
---|---|---|---|
+ | Addition | 5 + 2 | 7 |
- | Subtraction | 5 - 2 | 3 |
* | Multiplication | 5 * 2 | 10 |
/ | Division | 5 / 2 | 2.5 |
% | Modulus (remainder) | 5 % 2 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
++ | Increment | x++ | x = x + 1 |
-- | Decrement | x-- | x = x - 1 |
2οΈβ£ Assignment Operators
Used to assign values.
Operator | Example | Equivalent To |
---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
**= | x **= 2 | x = x ** 2 |
3οΈβ£ Comparison Operators
Used to compare values (returns true
or false
).
Operator | Description | Example | Result |
---|---|---|---|
== | Equal to (value only) | 5 == "5" | true |
=== | Strict equal (value + type) | 5 === "5" | false |
!= | Not equal (value only) | 5 != "5" | false |
!== | Strict not equal (value + type) | 5 !== "5" | true |
> | Greater than | 7 > 5 | true |
< | Less than | 7 < 5 | false |
>= | Greater or equal | 5 >= 5 | true |
<= | Less or equal | 3 <= 5 | true |
4οΈβ£ Logical Operators
Used with boolean (true
/ false
).
Operator | Description | Example | Result |
---|---|---|---|
&& | Logical AND | true && false | false |
|| | Logical OR | `true | |
! | Logical NOT | !true | false |
5οΈβ£ Bitwise Operators (works on 32-bit numbers)
Operator | Description | Example | Result |
---|---|---|---|
& | AND | 5 & 1 | 1 |
| | OR | 5 | 1 | 5 |
^ | XOR | 5 ^ 1 | 4 |
~ | NOT | ~5 | -6 |
<< | Left shift | 5 << 1 | 10 |
>> | Right shift | 5 >> 1 | 2 |
6οΈβ£ Ternary Operator (Conditional)
Shorthand for if...else
.
let age = 18;
let result = (age >= 18) ? "Adult" : "Minor";
console.log(result); // "Adult"
7οΈβ£ Type Operators
Operator | Description | Example | Result |
---|---|---|---|
typeof | Returns type of variable | typeof 123 | "number" |
instanceof | Checks if object is an instance of a class | arr instanceof Array | true |
β Summary
- Arithmetic β
+ - * / % ** ++ --
- Assignment β
= += -= *= /= %= **=
- Comparison β
== === != !== > < >= <=
- Logical β
&& || !
- Bitwise β
& | ^ ~ << >>
- Ternary β
condition ? trueValue : falseValue
- Type β
typeof
,instanceof