Operators

Arithmetic, comparison, logical

JavaScript Operators

Operators are symbols that perform operations on values (operands). JavaScript has several types of operators.

Arithmetic Operators

Perform mathematical calculations:

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... (division)
console.log(a % b);  // 1 (modulus/remainder)
console.log(a ** b); // 1000 (exponentiation, a to the power of b)

// Increment and decrement
let count = 5;
count++;   // 6 (post-increment)
++count;   // 7 (pre-increment)
count--;   // 6 (post-decrement)
--count;   // 5 (pre-decrement)

Comparison Operators

Compare values and return boolean results:

// Equality operators
console.log(5 == "5");   // true (loose equality, converts types)
console.log(5 === "5");  // false (strict equality, no type conversion)
console.log(5 != "5");   // false
console.log(5 !== "5");  // true

// Relational operators
console.log(10 > 5);     // true
console.log(10 < 5);     // false
console.log(10 >= 10);   // true
console.log(10 <= 5);    // false

⚠️ Always use === and !==

The loose equality operators (== and !=) perform type coercion, which can lead to unexpected results. Always use strict equality (=== and !==).

Logical Operators

Combine or invert boolean values:

const isActive = true;
const isAdmin = false;

// AND operator (&&) - both must be true
console.log(isActive && isAdmin);  // false

// OR operator (||) - at least one must be true
console.log(isActive || isAdmin);  // true

// NOT operator (!) - inverts the boolean
console.log(!isActive);  // false
console.log(!isAdmin);   // true

// Complex conditions
const age = 25;
const hasLicense = true;
const canDrive = age >= 18 && hasLicense;  // true

Assignment Operators

Assign and modify values:

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 %= 5;   // x = x % 5;  → 1
x **= 3;  // x = x ** 3; → 1

String Operators

The + operator concatenates strings:

const firstName = "John";
const lastName = "Doe";
const fullName = firstName + " " + lastName;  // "John Doe"

// With template literals (preferred)
const greeting = `Hello, ${firstName} ${lastName}!`;  // "Hello, John Doe!"

Ternary Operator

A shorthand for if-else statements:

// Syntax: condition ? valueIfTrue : valueIfFalse
const age = 20;
const status = age >= 18 ? "adult" : "minor";  // "adult"

// Can be nested (but avoid deep nesting)
const score = 85;
const grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";  // "B"

Nullish Coalescing Operator (??)

Returns the right operand when the left is null or undefined:

const name = null;
const defaultName = "Guest";

const displayName = name ?? defaultName;  // "Guest"

// Difference from || operator
console.log(0 || 10);   // 10 (0 is falsy)
console.log(0 ?? 10);   // 0 (0 is not null/undefined)

console.log("" || "default");   // "default"
console.log("" ?? "default");   // ""

Optional Chaining (?.)

Safely access nested properties that might not exist:

const user = {
  name: "Alice",
  address: {
    city: "New York"
  }
};

// Without optional chaining (can throw error)
// console.log(user.address.street.number);  // Error!

// With optional chaining (returns undefined)
console.log(user.address?.street?.number);  // undefined

// Works with arrays and functions too
const users = null;
console.log(users?.[0]);  // undefined

const greet = null;
console.log(greet?.());  // undefined

Spread Operator (...)

Expands iterables (arrays, objects) into individual elements:

// With arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];  // [1, 2, 3, 4, 5, 6]

// With objects
const user = { name: "Alice", age: 30 };
const updatedUser = { ...user, age: 31 };  // { name: "Alice", age: 31 }

// Function arguments
const numbers = [1, 2, 3, 4, 5];
console.log(Math.max(...numbers));  // 5

✓ Best Practices

  • • Always use === and !== instead of == and !=
  • • Use ?? when you want to check for null/undefined specifically
  • • Use optional chaining (?.) to safely access nested properties
  • • Use template literals instead of string concatenation for readability
  • • Keep ternary expressions simple—use if-else for complex logic