Script Valley
JavaScript Tutorial for Beginners to Advanced
JavaScript Basics: Variables, Data Types, and OperatorsLesson 2.3

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); // 9

Comparison 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);      // true

Logical 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 boolean

The 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