Conditions and loops
ECMAScript 2026
A condition lets the program choose an action. A loop lets it repeat an action. First try each idea with one simple rule.
On this page
Choose a branch with if, else if, and else
A condition is an expression JavaScript evaluates to make a decision. Code between braces forms a block. If the first condition is true it runs that block. Otherwise it checks else if. The final else covers what is left.
How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.
const quantity = 3;
if (quantity >= 5) {
console.log("Group order");
} else if (quantity >= 1) {
console.log("Regular order");
} else {
console.log("Choose at least one item");
}
What to expect The result is “Regular order”. Try 5 and 0 to check the two boundaries.
Match an exact value with switch
switch compares a single value against case labels. break exits the switch after the matching case runs. Without it, execution can continue into the next case. default handles unmatched values.
How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.
const productCode = "P";
switch (productCode) {
case "P":
console.log("Pen");
break;
case "N":
console.log("Notebook");
break;
default:
console.log("Unknown product");
}
What to expect It prints Pen. Change the code to N or X to try the other cases.
Repeat a counted task with for
A for loop has a start, a test, and an update. JavaScript runs the start once. Before each pass it tests the condition. After each pass it runs the update. itemNumber += 1 adds one to itemNumber.
How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.
for (let itemNumber = 1; itemNumber <= 3; itemNumber += 1) {
console.log("Item", itemNumber);
}
What to expect Item 1, Item 2, and Item 3 appear on separate lines. The next test fails when itemNumber reaches 4.
Repeat while a condition is true
while tests before every pass. Update the variables it checks so the condition can become false. break stops the current loop; continue starts the next pass early. Place the update where it will still run on any pass that continues.
How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.
let remaining = 3;
while (remaining > 0) {
remaining -= 1;
if (remaining === 1) continue;
console.log(remaining);
}
What to expect The Console prints 2 and 0. The loop skips printing 1 and stops once the condition becomes false.