Skip to content

Control Flow

Control flow determines how your program executes step by step.

Instead of running line by line blindly, JavaScript uses conditions and loops to:

  • Make decisions
  • Repeat tasks
  • Control execution paths

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

Used to execute code based on conditions.

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]

Short form of if-else.

let result = age >= 18 ? "Adult" : "Minor";

graph TD A[Condition 1] --> B{AND / OR} C[Condition 2] --> B B --> D[Result]

Used when checking multiple fixed values.

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 tasks efficiently.


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

Best when number of iterations is known.

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

Runs while condition is true.

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

Runs at least once.

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

Used for iterating object keys.

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

Used for iterating iterables (arrays, strings).

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

Array method for iteration.

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

for

Use when iteration count is known.

while

Use when condition-based looping.

do...while

Use when loop must run at least once.

for...in

Use for objects (keys).

for...of

Use for arrays and iterables (values).

forEach

Use for clean array iteration (no break).


for (let i = 0; i < 5; i++) {
if (i === 2) continue;
if (i === 4) break;
console.log(i);
}
  • break → exits loop
  • continue → skips iteration