JavaScript Operators & Expressions
Operators perform operations on values and variables.
Arithmetic Operators
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 (remainder)
a ** b // 1000 (exponentiation)
Assignment Operators
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++; // increment by 1
x--; // decrement by 1
Comparison Operators
Equality
// Loose equality (type conversion)
5 == "5" // true
null == undefined // true
// Strict equality (no type conversion)
5 === "5" // false
5 === 5 // true
null === undefined // false
Tip: Always use === to avoid unexpected type coercion.
Relational
5 > 3 // true
5 < 3 // false
5 >= 5 // true
5 <= 4 // false
Logical Operators
// AND — both must be true
true && false // false
// OR — at least one must be true
true || false // true
// NOT — inverts value
!true // false
// Nullish coalescing — uses right if null/undefined
null ?? "default" // "default"
0 ?? "default" // 0 (not null/undefined)
Remember: ?? only falls back on null/undefined. || falls back on any falsy value.
Ternary Operator
let age = 18;
let status = age >= 18 ? "Adult" : "Minor";
Format: condition ? valueIfTrue : valueIfFalse
Spread Operator
// Array spread
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
// Object spread
let obj1 = { a: 1, b: 2 };
let obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
Best Practices
- Use strict equality — Always
===instead of== - Use
??for defaults — Only falls back onnull/undefined - Use ternary for simple conditions — Avoid nesting
- Use spread operator — Instead of
concat/manual copying - Use parentheses — When unsure about precedence
Common Mistakes
- Loose equality — Use
===for type safety - Confusing
=and===— Assignment vs comparison - Using
||for defaults — Use??to allow0and"" - Overcomplicating ternaries — Keep readable
- Forgetting operator precedence — Use parentheses