Step: Basics | Player: 03_Operators and_Expressions
Learning Objectives
- You can branch the condition with
if / else if / else. - Understand the
switchstatement and its pitfalls (breakis missing). - Distinguish between
for,while,for...of, andfor...in. - You can control the repeat flow with
breakandcontinue. - You can write simple conditional expressions with the ternary operator.
1. Conditional branch if / else
The condition evaluates to truthy/falsy. If the branches become longer than 3, consider replacing them with switch or Data (object mapping).
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else grade = "C";
2. switch
Branch to case where the value matches exactly. If you omit break at the end of each case, it will fallthrough to the next case. Please indicate intentional fallthrough in comments.
switch (day) {
case "Sat":
case "Sun":
console.log("weekend");
break;
default:
console.log("weekdays");
}
3. Loop statement
for (let i = 0; i < n; i++)— When an index is needed.while (cond)— When only the termination condition is clear.for...of— Traverse iterable values such as arrays and strings.for...in— Key traversal of objects (not recommended for arrays).
for (const ch of "JS") console.log(ch);
for (const key in { a: 1, b: 2 }) console.log(key);
4. break / continue / ternary
break terminates the loop immediately, and continue skips the current round. The ternary operator is concise when determining a value based on a condition.
const label = age >= 18 ? "adult" : "minor";
Core example
| file | Contents covered |
|---|---|
01_if_else.js |
Grade branching by score + ternary |
02_switch.js |
switch fallthrough and group case |
03_for_loops.js |
for, while, for...of, for...in comparison |
04_break_continue.js |
Skip Even and Quit Early |
⚠️ Common Mistakes
- Unintended fallthrough occurs due to omission of
breakat the end of eachcaseinswitch. - When using
for (var i ...)and asynchronous callback together,iis shared and a bug occurs (usinglet). - Problem that the index is displayed as a string or the order is not guaranteed when using
for...inin the array. - Omitting to change the exit condition after creating an infinite loop.
- Code that overlaps too many ternaries, making it difficult to read.
❓ Frequently Asked Questions (FAQ)
Q1. Should I use for or forEach? A. If you need break in the middle, use for/for...of. For simple traversal, forEach is also good.
Q2. Should switch always be avoided? A. It is easier to read if the branches are clearly value-based. If your branching becomes complex, switch to object mapping.
Q3. Doesn't continue confuse the code flow? A. When reducing deep nesting with guard clauses, it actually improves readability.