JavaScript Fundamentals: Control Flow

· 12 min read · beginner
control-flow if-else loops beginner
Part 4 of the javascript-fundamentals series

Control flow determines the order in which your code executes. Without it, JavaScript would run line by line from top to bottom. With control flow, you can make decisions, repeat actions, and handle different conditions. This tutorial covers everything you need to direct the execution path of your JavaScript programs.

Conditional Statements

The if Statement

The if statement executes a block of code only when a specified condition evaluates to true.

const temperature = 25;

if (temperature > 20) {
  console.log("It's a warm day!");
}
// Output: It's a warm day!

The condition inside the parentheses must evaluate to a truthy or falsy value. In JavaScript, false, 0, "" (empty string), null, undefined, and NaN are falsy. Everything else is truthy.

if…else and else if

Use else to execute code when the condition is false, and else if to test multiple conditions.

const score = 75;
let grade;

if (score >= 90) {
  grade = 'A';
} else if (score >= 80) {
  grade = 'B';
} else if (score >= 70) {
  grade = 'C';
} else {
  grade = 'F';
}

console.log(`You got a ${grade}`);
// Output: You got a C

JavaScript evaluates conditions from top to bottom, stopping at the first truthy condition.

The Ternary Operator

For simple conditions, the ternary operator offers a compact alternative:

const age = 20;
const status = age >= 18 ? 'adult' : 'minor';
console.log(status);
// Output: adult

Use ternaries for simple assignments, but prefer if...else for complex logic to maintain readability.

The switch Statement

When you need to compare one value against multiple possibilities, switch provides cleaner syntax than chained else if statements.

const day = 'Monday';

switch (day) {
  case 'Monday':
  case 'Tuesday':
  case 'Wednesday':
  case 'Thursday':
  case 'Friday':
    console.log('Weekday');
    break;
  case 'Saturday':
  case 'Sunday':
    console.log('Weekend');
    break;
  default:
    console.log('Invalid day');
}
// Output: Weekday

Key points about switch:

  • The break keyword stops execution and exits the switch
  • Without break, execution “falls through” to the next case (like Monday through Friday above)
  • The default case runs when no other case matches
  • Comparison uses strict equality (===)

Loops

Loops repeat a block of code multiple times. JavaScript provides several loop types for different scenarios.

The for Loop

The for loop repeats code a specific number of times:

for (let i = 0; i < 5; i++) {
  console.log(`Iteration ${i}`);
}
// Output:
// Iteration 0
// Iteration 1
// Iteration 2
// Iteration 3
// Iteration 4

The three parts of a for loop:

  1. Initialization: let i = 0 — runs once before starting
  2. Condition: i < 5 — checked before each iteration
  3. Update: i++ — runs after each iteration

The while Loop

The while loop repeats as long as a condition is true:

let count = 0;

while (count < 3) {
  console.log(count);
  count++;
}
// Output:
// 0
// 1
// 2

Be careful with while loops — if the condition never becomes false, you’ll create an infinite loop.

The do…while Loop

This variant always executes at least once, because the condition is checked after the code runs:

let num = 0;

do {
  console.log(num);
  num++;
} while (num < 3);
// Output:
// 0
// 1
// 2

for…of Loop

The for...of loop iterates over iterable objects like arrays and strings:

const fruits = ['apple', 'banana', 'cherry'];

for (const fruit of fruits) {
  console.log(fruit);
}
// Output:
// apple
// banana
// cherry

This is the cleanest way to loop through arrays when you don’t need the index.

for…in Loop

The for...in loop iterates over enumerable properties of an object:

const person = {
  name: 'Alice',
  age: 30,
  city: 'London'
};

for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}
// Output:
// name: Alice
// age: 30
// city: London

Loop Control: break and continue

break

The break statement immediately exits the nearest loop:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break;
  }
  console.log(i);
}
// Output: 0 1 2 3 4

continue

The continue statement skips the current iteration and moves to the next one:

for (let i = 0; i < 5; i++) {
  if (i === 2) {
    continue;
  }
  console.log(i);
}
// Output: 0 1 3 4

Practical Example: FizzBuzz

Here’s a classic programming challenge that combines everything you’ve learned:

for (let i = 1; i <= 15; i++) {
  if (i % 3 === 0 && i % 5 === 0) {
    console.log('FizzBuzz');
  } else if (i % 3 === 0) {
    console.log('Fizz');
  } else if (i % 5 === 0) {
    console.log('Buzz');
  } else {
    console.log(i);
  }
}
// Output:
// 1
// 2
// Fizz
// 4
// Buzz
// Fizz
// 7
// 8
// Fizz
// Buzz
// 11
// Fizz
// 13
// 14
// FizzBuzz

This example demonstrates how control flow lets you handle multiple conditions and create interesting patterns.

Summary

Control flow is fundamental to programming in JavaScript. You now understand:

  • Conditional statements: if, else if, else, and the ternary operator for making decisions
  • Switch statements: Clean syntax for comparing one value against many cases
  • Loops: for, while, do...while, for...of, and for...in for repeating code
  • Loop control: break to exit loops early and continue to skip iterations

These concepts form the backbone of JavaScript logic. Practice with real-world problems like the FizzBuzz challenge to solidify your understanding.