Skip to main content

3. Conditionals & Loops

Control flow is how you make your code smart—deciding what to do, when, and how many times. JavaScript offers powerful tools for branching and repetition. Here’s how to use them like a pro.


3.1 Conditional Statements

if, else if, else

Run code only if a condition is true:

let age = 20;
if (age >= 18) {
console.log('Adult');
} else if (age >= 13) {
console.log('Teenager');
} else {
console.log('Child');
}

switch – Multiple Choices

Cleaner than many if/else if blocks:

let color = 'blue';
switch (color) {
case 'red':
console.log('Red!');
break;
case 'blue':
console.log('Blue!');
break;
default:
console.log('Other color');
}

Ternary Operator

Short, inline condition:

let isMember = true;
let price = isMember ? 10 : 20;

3.2 Loops

for Loop

Repeat a block a set number of times:

for (let i = 0; i < 3; i++) {
console.log(i); // 0, 1, 2
}

while and do...while

let n = 0;
while (n < 3) {
console.log(n);
n++;
}

let m = 0;
do {
console.log(m);
m++;
} while (m < 3);

Array Loops

forEach

['a', 'b', 'c'].forEach(letter => console.log(letter));

for...of (arrays, iterables)

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

for...in (objects)

let obj = {a: 1, b: 2};
for (let key in obj) {
console.log(key, obj[key]);
}

3.3 Recursion

When a function calls itself. Useful for problems that break into smaller subproblems.

function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive call
}
console.log(factorial(5)); // 120

Tip: Always define a base case to avoid infinite loops.


3.4 Loop Controls

break and continue

for (let i = 0; i < 5; i++) {
if (i === 3) break; // exits loop
if (i % 2 === 0) continue; // skips even numbers
console.log(i); // 1
}

Next: Functions in JavaScript