CPCODELAB
JavaScript

Operators

7 min read

JavaScript Operators

Operators let you perform arithmetic, comparisons, logical tests, and assignments. Knowing operator precedence saves you from needing excessive parentheses.

Arithmetic and Assignment

javascript
let x = 10;
x += 5;  // 15  (x = x + 5)
x -= 3;  // 12
x *= 2;  // 24
x /= 4;  // 6
x **= 2; // 36  (exponentiation)
x %= 5;  // 1   (remainder)

// Increment / decrement
x++;  // post-increment: returns x then increments
++x;  // pre-increment: increments then returns x

Logical Operators

&& (AND) and || (OR) are short-circuit operators — they return one of their operands, not necessarily a boolean. This is useful for default values and guard expressions.

javascript
const name = "" || "Anonymous";   // "Anonymous"
const debug = true && "enabled";  // "enabled"

// Logical assignment (ES2021)
let a = null;
a ??= "default";   // assigns only if a is null/undefined
let b = 0;
b ||= 42;          // assigns only if b is falsy
let c = 1;
c &&= c * 2;       // assigns only if c is truthy

Use the ?? (nullish coalescing) operator when you want to fall back only on null or undefined — not on 0, "", or false, which || would incorrectly treat as missing.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises