Operators
arithmetic, comparison, logical
Skills taught: js.operators, js.arithmetic, js.comparison, js.logical
Arithmetic operators
10 + 3 // 13 — addition
10 - 3 // 7 — subtraction
10 * 3 // 30 — multiplication
10 / 3 // 3.333... — division
10 % 3 // 1 — remainder (modulo)
10 ** 2 // 100 — exponentiation (10 squared)
// Assignment shorthand
let x = 10;
x += 5; // x = 15 (same as x = x + 5)
x -= 3; // x = 12
x *= 2; // x = 24
x /= 4; // x = 6
x++; // x = 7 (increment by 1)
x--; // x = 6 (decrement by 1)
Comparison operators
// Always use strict equality
5 === 5 // true — strict equal (same type AND value)
5 !== 3 // true — strict not equal
5 > 3 // true — greater than
5 < 3 // false — less than
5 >= 5 // true — greater than or equal
5 <= 4 // false — less than or equal
// Loose equality — AVOID
5 == '5' // true — converts types
0 == false // true — confusing
null == undefined // true — very confusing
// String comparison (lexicographic)
'apple' < 'banana' // true — alphabetical order
'Z' < 'a' // true — uppercase letters sort before lowercase
Logical operators
// AND (&&) — both must be true
true && true // true
true && false // false
// OR (||) — at least one must be true
true || false // true
false || false // false
// NOT (!) — flips true/false
!true // false
!false // true
// Short-circuit evaluation
const user = null;
const name = user && user.name; // null (stops early — user is falsy)
const display = name || 'Guest'; // 'Guest' (fallback when name is falsy)
// Nullish coalescing (??) — only falls back on null/undefined (not 0 or '')
const score = 0;
const display1 = score || 'No score'; // 'No score' (WRONG — 0 is falsy!)
const display2 = score ?? 'No score'; // 0 (CORRECT — 0 is not null/undefined)
Optional chaining (?.) and nullish coalescing (??)
const user = { profile: { name: 'Prashant' } };
const guestUser = null;
// Without optional chaining — throws if user is null
const name1 = user.profile.name; // 'Prashant'
const name2 = guestUser.profile.name; // TypeError: Cannot read properties of null
// With optional chaining — safely returns undefined
const name3 = guestUser?.profile?.name; // undefined (no error)
const name4 = guestUser?.profile?.name ?? 'Guest'; // 'Guest'
Frequently Asked Questions
What does NaN mean?
NaN stands for 'Not a Number'. It is the result of invalid numeric operations like 0/0 or parseInt('hello'). Confusingly, typeof NaN === 'number'. Use Number.isNaN(value) to check for it.
What is the difference between ++ before and after a variable?
x++ (post-increment) returns the current value THEN increments. ++x (pre-increment) increments first THEN returns the new value. In most cases this distinction doesn't matter — the end result (x is incremented) is the same.