TutorialsJSControl Flow
Share:

Control Flow

intermediate

Part of Core JavaScript

Theory

Control flow determines the order in which code executes. JavaScript provides conditionals for branching and loops for repetition.

Conditionals:

  • if/else — the most common conditional. if (condition) { ... } else if (condition) { ... } else { ... }
  • switch — evaluates an expression against multiple case labels. Use break to prevent fall-through
  • Ternary operator condition ? exprIfTrue : exprIfFalse — a concise inline conditional for simple cases

Truthy and falsy values determine how conditions evaluate. Falsy values: false, 0, "" (empty string), null, undefined, NaN. Everything else is truthy, including "0", [], and {}.

Logical operators combine and manipulate conditions:

  • && (AND) — returns the first falsy value or the last truthy value
  • || (OR) — returns the first truthy value or the last falsy value
  • ! (NOT) — negates a boolean value
  • Nullish coalescing ?? — returns the right operand only if the left is null or undefined

Loops repeat code while a condition is true:

  • for — classic loop with init, condition, and increment: for (let i = 0; i < n; i++)
  • while — loops while a condition is true: while (condition) { ... }
  • do...while — executes at least once, then checks condition
  • for...of — iterates over iterable values (arrays, strings, Maps, Sets)
  • forEach — array method that executes a function for each element

Break and continue: break exits a loop entirely. continue skips to the next iteration.

Control Flow Examples
javascript
Loop Examples
javascript

Exercises

FizzBuzz

easy

Write a for loop that iterates from 1 to 15. For multiples of 3, print 'Fizz'. For multiples of 5, print 'Buzz'. For multiples of both 3 and 5, print 'FizzBuzz'. Otherwise, print the number.

Starter Code:

for (let i = 1; i <= 15; i++) {\n  // Your code here\n}

Expected Output:

1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz

Mini Quiz

Mini Quiz