JavaScript Operators
arithmetic, assignment, comparison, logical, ternary, nullish coalescing, optional chaining
JavaScript Operators
Operators are symbols that perform operations on values. JavaScript has a rich set of operators for arithmetic, comparisons, logical decisions, and more. Mastering operators is foundational to writing any meaningful JavaScript code.
Arithmetic Operators
const a = 10;
const b = 3;
console.log(a + b); // 13 โ addition
console.log(a - b); // 7 โ subtraction
console.log(a * b); // 30 โ multiplication
console.log(a / b); // 3.333...
console.log(a % b); // 1 โ remainder (modulo)
console.log(a ** b); // 1000 โ exponentiation (ES7)Assignment Operators
Compound assignment operators update a variable in one step.
let count = 0;
count += 1; // count = 1
count += 4; // count = 5
count -= 2; // count = 3
count *= 3; // count = 9
console.log(count); // 9Comparison Operators
Always use === and !== for comparisons. They check both value and type without coercion.
console.log(5 === 5); // true
console.log(5 === '5'); // false โ different types
console.log(10 !== 20); // true
console.log(7 > 3); // true
console.log(3 >= 3); // trueLogical Operators
const isLoggedIn = true;
const hasPermission = false;
console.log(isLoggedIn && hasPermission); // false โ both must be true
console.log(isLoggedIn || hasPermission); // true โ at least one is true
console.log(!isLoggedIn); // false โ flips the booleanThe Ternary Operator
The ternary operator is a concise one-line if/else. It evaluates a condition and returns one of two values.
const age = 20;
const status = age >= 18 ? 'adult' : 'minor';
console.log(status); // 'adult'Nullish Coalescing and Optional Chaining
The nullish coalescing operator ?? returns the right-hand value only when the left-hand value is null or undefined. The optional chaining operator ?. safely accesses nested properties without throwing an error if a value is null.
const username = null;
const displayName = username ?? 'Guest';
console.log(displayName); // 'Guest'
const user = { profile: { bio: 'Developer' } };
console.log(user?.profile?.bio); // 'Developer'
console.log(user?.address?.street); // undefined โ no error thrown