Operators and Control Flow

Site Admin · 11 Sep 2026 · 8 views

Operators and Control Flow

Operators perform actions on values. Control flow determines which code runs based on conditions and loops. These are the building blocks of any program.

Arithmetic Operators

let a = 10 + 3;    // 13 (addition)
let b = 10 - 3;    // 7  (subtraction)
let c = 10 * 3;    // 30 (multiplication)
let d = 10 / 3;    // 3.33 (division)
let e = 10 % 3;    // 1  (remainder)
let f = 2 ** 3;    // 8  (exponentiation)

Comparison and Logical Operators

5 == "5"    // true  (loose equality - avoid)
5 === "5"   // false (strict equality - use)
5 !== "5"   // true  (strict inequality)

let isAdult = age >= 18;
let isPremium = price > 50 && hasSubscription;
let canEnter = isAdult || hasPermission;
let notLoggedOut = !isLoggedOut;

Conditionals

function checkScore(score) {
    if (score >= 90) {
        return "A";
    } else if (score >= 80) {
        return "B";
    } else if (score >= 70) {
        return "C";
    } else {
        return "F";
    }
}

// Switch statement
function getDayName(day) {
    switch (day) {
        case 0: return "Sunday";
        case 1: return "Monday";
        case 2: return "Tuesday";
        default: return "Unknown";
    }
}

Ternary Operator

let access = isAdmin ? "full" : "limited";

Loops

// for loop
for (let i = 0; i < 5; i++) {
    console.log(i);  // 0, 1, 2, 3, 4
}

// while loop
let count = 0;
while (count < 3) {
    count++;
}

// for...of (array iteration)
for (const item of ["a", "b", "c"]) {
    console.log(item);
}

// for...in (object keys)
const user = {name: "Alice", age: 30};
for (const key in user) {
    console.log(key, user[key]);
}

Key Points

  • Operators: arithmetic (+ - * / % **), comparison, and logical.
  • Use === and !== for strict comparison.
  • Use if/else if/else for ranges, switch for exact matches.
  • The ternary operator ? is a compact if/else.
  • for...of iterates arrays; for...in iterates object keys.
Share this post:

Comments (0)

Please login or register to comment.