Operators
## Learning Objectives
- Master arithmetic, comparison, and logical operators
- Understand bitwise operators
- Learn about the spread and ternary operators
## Arithmetic Operators
```javascript
let a = 10;
let b = 3;
a + b // 13 (addition)
a - b // 7 (subtraction)
a * b // 30 (multiplication)
a / b // 3.333... (division)
a % b // 1 (modulo - remainder)
a ** b // 1000 (exponentiation)
```
### Increment and Decrement
```javascript
let x = 5;
// Prefix
++x; // x is now 6, returns 6
--x; // x is now 5, returns 5
// Postfix
x++; // returns 5, x is now 6
x--; // returns 6, x is now 5
```
## Comparison Operators
### Loose Equality (==)
```javascript
5 == "5" // true (string coerced to number)
true == 1 // true
null == undefined // true
```
### Strict Equality (===)
```javascript
5 === "5" // false (different types)
true === 1 // false
null === undefined // false
```
### Relational Operators
```javascript
10 > 5 // true
10 < 5 // false
10 >= 10 // true
10 <= 5 // false
// String comparison
"apple" < "banana" // true (alphabetical)
"Apple" < "apple" // true (lowercase > uppercase in ASCII)
```
## Logical Operators
```javascript
// AND
true && true // true
true && false // false
// OR
true || false // true
false || false // false
// NOT
!true // false
!!true // true
// Short-circuit evaluation
true || console.log("not printed")
false || console.log("printed")
// Practical examples
if (age >= 18 && hasLicense) {
console.log("Can drive");
}
if (isAdmin || hasPermission) {
console.log("Access granted");
}
```
## Assignment Operators
```javascript
let x = 10;
x += 5; // x = x + 5 -> 15
x -= 3; // x = x - 3 -> 12
x *= 2; // x = x * 2 -> 24
x /= 4; // x = x / 4 -> 6
x %= 5; // x = x % 5 -> 1
x **= 2; // x = x ** 2 -> 1
```
## Bitwise Operators
```javascript
// Binary representations
// 5 = 00000000000000000000000000000101
// 3 = 00000000000000000000000000000011
5 & 3 // 1 (AND: 00001)
5 | 3 // 7 (OR: 00111)
5 ^ 3 // 6 (XOR: 00110)
~5 // -6 (NOT)
~0 // -1
// Bitwise shifts
2 << 1 // 4 (left shift)
8 >> 1 // 4 (right shift)
-8 >>> 1 // 2147483644 (unsigned right shift)
```
## Ternary Operator
```javascript
// condition ? valueIfTrue : valueIfFalse
const status = age >= 18 ? "adult" : "minor";
const greeting = isLoggedIn ? `Hello, ${name}` : "Hello, Guest";
// Nested ternary (avoid when possible)
const type = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";
```
## Nullish Operators
### Nullish Coalescing (??)
```javascript
// Returns right side if left is null or undefined
const foo = null ?? "default"; // "default"
const bar = 0 ?? "default"; // 0
const baz = "" ?? "default"; // ""
const qux = false ?? "default"; // false
// Different from ||
const orResult = 0 || "default"; // "default"
const nullishResult = 0 ?? "default"; // 0
```
### Optional Chaining (?.)
```javascript
const user = {
name: "Alice",
address: {
city: "New York"
}
};
user?.name // "Alice"
user?.address?.city // "New York"
user?.phone?.number // undefined (no error!)
user.name.nonExistent // Error: Cannot read property...
```
## Typeof Operator
```javascript
typeof "hello" // "string"
typeof 123 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (historical bug)
typeof Symbol("x") // "symbol"
typeof {} // "object"
typeof [] // "object"
typeof function(){} // "function"
```
## Comma Operator
```javascript
// Evaluates left to right, returns rightmost value
let a = (1, 2, 3); // a = 3
// Common use in for loops
for (let i = 0, j = 10; i < j; i++, j--) {
console.log(i, j);
}
```
## Operator Precedence
Highest to lowest:
1. `()` (grouping)
2. `.` `[]` `?.` (member access)
3. `()` `new` (function call, new)
4. `!` `~` `++` `--` `typeof` `void` `delete` `await`
5. `**`
6. `*` `/` `%`
7. `+` `-`
8. `<<` `>>` `>>>`
9. `<` `<=` `>` `>=` `in` `instanceof`
10. `==` `!=` `===` `!==`
11. `&`
12. `^`
13. `|`
14. `&&`
15. `||`
16. `??`
17. `?:` (ternary)
18. `=` `+=` `-=` etc.
19. `,`
## Summary
- Use `===` instead of `==` to avoid type coercion issues
- Short-circuit evaluation with `&&` and `||` can simplify code
- The ternary operator is useful for simple conditional assignments
- Optional chaining (`?.`) simplifies null/undefined checks on nested properties
- Always check operator precedence or use parentheses for clarity
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →