Skip to content

Control Flow

Control flow simply means how your program runs, step by step.

Instead of just running every line blindly from top to bottom, JavaScript uses conditions and loops to:

  • Make decisions
  • Repeat tasks
  • Control which path the code takes
graph TD A[Start] --> B{Condition} B -->|True| C[Execute Block A] B -->|False| D[Execute Block B] C --> E[End] D --> E

These are used to run different code depending on a condition.

let score = 75;
if (score >= 90) {
console.log("A");
} else if (score >= 70) {
console.log("B");
} else {
console.log("C");
}
graph TD A[Condition] -->|True| B[Run if block] A -->|False| C[Run else block]

This is just a shorter way of writing an if-else statement.

let result = age >= 18 ? "Adult" : "Minor";
graph TD A[Condition 1] --> B{AND / OR} C[Condition 2] --> B B --> D[Result]

This is used when you need to check a value against several fixed options.

let day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Other day");
}

Loops are used to repeat a task again and again, without writing the same code many times.

graph TD A[Start] --> B{Condition} B -->|True| C[Execute Body] C --> B B -->|False| D[End]

This works best when you already know how many times you want to repeat something.

for (let i = 0; i < 5; i++) {
console.log(i);
}

This keeps running as long as the condition stays true.

let i = 0;
while (i < 5) {
console.log(i);
i++;
}

This always runs at least one time, even if the condition is false from the start.

let i = 0;
do {
console.log(i);
i++;
} while (i < 5);

This is used to go through the keys of an object, one by one.

let user = { name: "Sahil", age: 20 };
for (let key in user) {
console.log(key, user[key]);
}

This is used to go through iterables, like arrays and strings, one item at a time.

let arr = [10, 20, 30];
for (let value of arr) {
console.log(value);
}

This is a built-in array method used for looping through items.

let arr = [1, 2, 3];
arr.forEach((value, index) => {
console.log(value, index);
});

for

Use this when you already know how many times the loop should run.

while

Use this when the loop should keep going based on a condition.

do...while

Use this when the loop needs to run at least once, no matter what.

for...in

Use this for going through the keys of an object.

for...of

Use this for going through arrays and other iterables, value by value.

forEach

Use this for a clean way to loop through an array (note that you cannot use break with it).

for (let i = 0; i < 5; i++) {
if (i === 2) continue;
if (i === 4) break;
console.log(i);
}
  • break -> this stops the loop completely and exits it.
  • continue -> this skips just the current step and moves on to the next one.