Control Flow: if else switch for while
Branch with if/else and switch, loop with for and while, and use break and continue to control iteration.
Control Flow: if else switch for while is a free Frontend Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is Control Flow?
Control flow determines which code runs and how many times. JavaScript provides conditionals (if/else, switch) and loops (for, while, do/while) to direct the execution path based on conditions and data.
if / else if / else
The most fundamental conditional. The condition in parentheses is evaluated as truthy/falsy. Multiple conditions chain with else if. The final else is a catch-all fallback.
const score = 75;
if (score >= 90) {
console.log('A');
} else if (score >= 80) {
console.log('B');
} else if (score >= 70) {
console.log('C');
} else {
console.log('F');
}The Ternary Operator
The ternary operator is a compact inline if/else: condition ? trueValue : falseValue. Use it for simple assignments and JSX expressions. Avoid nesting ternaries — they become unreadable quickly.
const label = age >= 18 ? 'Adult' : 'Minor';
const icon = isActive ? '🟢' : '🔴';
// In JSX:
<span>{isLoggedIn ? 'Logout' : 'Login'}</span>switch Statement
switch compares a value against multiple cases using strict equality. Use break after each case to prevent fall-through. default handles unmatched values.
const day = 'Monday';
switch (day) {
case 'Saturday':
case 'Sunday':
console.log('Weekend');
break;
case 'Monday':
console.log('Start of work week');
break;
default:
console.log('Weekday');
}for Loop
The classic C-style for loop: initialiser; condition; increment. Best for iterating a known number of times or looping over arrays by index.
for (let i = 0; i < 5; i++) {
console.log(i); // 0 1 2 3 4
}
// Iterate array by index:
const names = ['Alice', 'Bob', 'Carol'];
for (let i = 0; i < names.length; i++) {
console.log(names[i]);
}for...of Loop
for...of iterates over the values of any iterable (arrays, strings, Maps, Sets). Cleaner than the index-based for loop when you don't need the index.
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}
for (const char of 'hello') {
console.log(char); // h e l l o
}for...in Loop
for...in iterates over the enumerable property keys of an object. Don't use it on arrays — use for...of or array methods instead.
const user = { name: 'Alice', age: 30, role: 'admin' };
for (const key in user) {
console.log(`${key}: ${user[key]}`);
}while Loop
The while loop executes as long as its condition is truthy. Use it when the number of iterations isn't known in advance — for example, reading input until the user enters a valid value.
let attempts = 0;
let success = false;
while (!success && attempts < 3) {
// try something
attempts++;
success = Math.random() > 0.5; // simulate
}
console.log(`Done in ${attempts} attempts`);do...while Loop
do...while executes the body at least once before checking the condition. Useful when the body must run before you can evaluate the exit condition.
let input;
do {
input = prompt('Enter a number:');
} while (isNaN(Number(input)));break and continue
break exits the current loop immediately. continue skips the rest of the current iteration and moves to the next. Both work in for, while, and do/while loops.
for (let i = 0; i < 10; i++) {
if (i === 3) continue; // skip 3
if (i === 7) break; // stop at 7
console.log(i); // 0 1 2 4 5 6
}Short-Circuit Evaluation
&& returns the first falsy value or the last value. || returns the first truthy value or the last value. ?? (nullish coalescing) returns the right side only if left is null or undefined.
const name = user && user.name; // null if user is falsy
const label = name || 'Anonymous'; // 'Anonymous' if name is falsy
const port = config.port ?? 3000; // 3000 only if port is null/undefinedQuick Check
Which loop is guaranteed to execute its body at least once?
Recap: JavaScript Control Flow
if/else for branching. Switch for multiple discrete values. for loop for known iterations. for...of for iterables. while for unknown iterations. do...while for at-least-one. break exits loops. continue skips iterations. Short-circuit operators for concise conditionals.
Frequently asked questions
Is the “Control Flow: if else switch for while” lesson free?
Yes — the full text of “Control Flow: if else switch for while” is free to read here on the web, and the Frontend Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Frontend Academy course, upgrade to CoddyKit PRO.
What will I learn in “Control Flow: if else switch for while”?
Branch with if/else and switch, loop with for and while, and use break and continue to control iteration. You practise Frontend Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Frontend Academy?
No prior experience is required. Frontend Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Control Flow: if else switch for while” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Frontend Academy lesson?
Yes. Every Frontend Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Variables: let const var and Scope
- Data Types: string number boolean null undefined
- Functions: declarations expressions arrow functions
- Control Flow: if else switch for while