Back to JavaScript Notes
Topic #294

Control Flow

You will be able to explain and write JavaScript control flow using conditionals, loops, and try/catch/finally to decide what code runs, how many times it runs, and how errors are handled.

What it is

Control flow is the order in which JavaScript statements execute. By default, code runs from top to bottom. Conditionals such as if and switch choose one branch. Loops such as for and while repeat a block. Exceptions use throw, catch, and finally to jump out of normal flow when something goes wrong. Related terms include branch, iteration, loop body, exception, and cleanup.

Why it matters

  • It lets programs respond to different inputs without duplicating code.
  • It prevents invalid states by checking conditions before acting.
  • It makes repetitive work manageable, such as processing arrays.
  • It keeps error handling separate from normal logic.
  • It helps you reason about execution order, especially with return, break, and finally.

Syntax or steps

The smallest useful control-flow pattern combines a decision, a loop, and error handling:

if (condition) {
  // run when condition is true
} else {
  // run when condition is false
}

for (let i = 0; i < count; i++) {
  // repeat count times
}

try {
  // code that may throw
} catch (e) {
  // handle the error
} finally {
  // cleanup that always runs
}

Read it as: test a condition, repeat work while needed, and protect risky code with a fallback path.

Example

function processOrder(order) {
  let total = 0;

  try {
    if (!order || !Array.isArray(order.items)) {
      throw new Error("Missing order items");
    }

    for (const item of order.items) {
      if (item.price < 0) {
        throw new Error("Negative price");
      }
      total += item.price;
    }

    return total;
  } catch (e) {
    console.error(e.message);
    return 0;
  } finally {
    console.log("Processing finished");
  }
}

console.log(processOrder({ items: [{ price: 10 }, { price: 5 }] }));
console.log(processOrder(null));

Part by part:

  • processOrder starts with total = 0, then enters try.
  • The if checks whether the input has an array of items. If not, throw jumps to catch.
  • The for loop visits each item. If a price is negative, it throws another error.
  • If no error occurs, return total is reached, but finally runs first.
  • The first call prints Processing finished, then 15. The second call prints the error message, then Processing finished, then 0.

Common mistakes

  • Forgetting braces. A single-statement if can become misleading when edited. Always use braces for clarity.
  • Returning from finally. A return inside finally can hide the original result or error. Keep finally for cleanup only.
  • Creating infinite loops. If the loop condition never becomes false, the program freezes. Make sure the loop variable changes each pass.
  • Using exceptions for normal flow. Expected cases, such as an empty cart, should usually use conditionals, not throw.

When to use it

Control flow is not one tool; it is a set of tools. Choose the smallest construct that matches the problem.

ConstructUse whenPrefer alternative when
if / elseThere are two or three clear branches.Many discrete values match one variable; use switch.
for / whileYou need to repeat work.You only need to transform an array; use map or forEach.
try / catchAn operation may fail unexpectedly.The failure is a normal business rule; use validation and if.
finallyCleanup must happen after success or failure.Cleanup is only needed on success; put it after the risky call.

Practice

Guided exercise: Write a function that loops through the numbers 1 to 5, skips 3, and returns the sum. Expected output: 12.

Challenge: Modify processOrder so it also rejects items without a price property. Hint: use if (typeof item.price !== "number") inside the loop.

Quick check

Question: Does finally run if the try block returns a value?

Answer: Yes. JavaScript runs finally before the function actually returns.

Summary

Control flow shapes a program by deciding which statements run, how often they run, and what happens when something fails. In JavaScript, conditionals branch, loops repeat, and try/catch/finally handles exceptional paths while keeping cleanup predictable.

Want to go beyond the notes?

Join Coding Now Tech Institute's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Control Flow – FAQs

Quick answers about learning Control Flow in JavaScript.

This free note from Coding Now Tech Institute explains Control Flow in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on Coding Now Tech Institute, including Control Flow, is 100% free with no signup required.
With focused practice, most students grasp Control Flow in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now