if, switch and loops
Code makes decisions with if / else and switch, and repeats work with loops. This note covers why the order of conditions matters, switch with break, for, while, for...of vs for...in, and break / continue.
4.1 Problem: wrong delivery charge
- Rule: ₹1000 or more = free delivery, ₹500 or more = ₹20, everything else = ₹40.
- For a total of 1200 the code prints Delivery: 20 instead of 0.
JavaScript
const total = 1200;let delivery; if (total >= 500) { delivery = 20;} else if (total >= 1000) { delivery = 0;} else { delivery = 40;} console.log("Delivery:", delivery);Output
> Delivery: 204.2 How an if / else chain is checked
- The chain is checked from top to bottom.
- Only the block of the first true condition runs; the rest are skipped.
- 1200 >= 500 was true first, so the 1000 condition was never checked.
- Rule: write the specific condition first and the general one later.
- Step 1
1.total = 1200
- Step 2
2.Check total >= 1000: true
- Step 3
3.Run that block: delivery = 0
- Step 4
4.Skip every else if / else below
- Step 5
5.Print Delivery: 0
Order matters: put the specific condition first
JavaScript
const total = 1200;let delivery; if (total >= 1000) { delivery = 0;} else if (total >= 500) { delivery = 20;} else { delivery = 40;} console.log("Delivery:", delivery);Output
> Delivery: 04.3 switch: one value, many cases
- Cleaner than a long if / else chain when one value is compared with many fixed values.
- switch compares with each case using strict equality (===).
- break stops the switch; default runs when no case matches.
JavaScript
const status = "shipped"; switch (status) { case "placed": console.log("Order confirmed"); break; case "shipped": console.log("On the way"); break; case "delivered": console.log("Delivered"); break; default: console.log("Unknown status");}Output
> On the way4.4 for loop: when you know the count
- Booking 3 seats on IRCTC: instead of copying code 3 times, use a for loop.
- Three parts: start (let i = 1), condition (i <= seats), update (i++).
JavaScript
const seats = 3; for (let i = 1; i <= seats; i++) { console.log("Booking seat", i);} console.log("Done");Output
> Booking seat 1> Booking seat 2> Booking seat 3> Done- Step 1
1.Start: let i = 1 (only once)
- Step 2
2.Condition: i <= 3? false ends the loop
- Step 3
3.Body: console.log runs
- Step 4
4.Update: i++, then back to the condition
- Step 5
5.Loop ends: "Done" is printed
The cycle repeats until the condition becomes false
4.5 while loop: when you don't know the count
- UPI payment retry: keep trying while the payment has not gone through and attempt <= 3.
- For the demo, the 2nd try succeeds (paid = attempt === 2).
- attempt++ is essential: forgetting it creates an infinite loop.
JavaScript
let attempt = 1;let paid = false; while (!paid && attempt <= 3) { console.log("Payment try", attempt); paid = attempt === 2; attempt++;} console.log(paid ? "Paid" : "Failed");Output
> Payment try 1> Payment try 2> Paid4.6 for...of and for...in
- for...of gives every value of an array (Shoes, Watch, Bag).
- for...in runs over the keys of an object (name, city); read the value with user[key].
- Checkpoint: for...in on an array gives the indexes as strings ("0", "1", "2"), so use for...of for arrays.
JavaScript
const cart = ["Shoes", "Watch", "Bag"]; for (const item of cart) { console.log(item);} const user = { name: "Riya", city: "Pune" }; for (const key in user) { console.log(key, user[key]);}Output
> Shoes> Watch> Bag> name Riya> city PuneJavaScript
const cart = ["Shoes", "Watch", "Bag"]; for (const i in cart) { console.log(i, typeof i);}Output
> 0 string> 1 string> 2 string4.7 break and continue
- continue skips the current round and jumps to the next (price 0 = out of stock).
- break stops the whole loop (an item above 1000), so 80 is never added.
- Total comes to 570.
JavaScript
const prices = [120, 0, 450, 2000, 80];let total = 0; for (const price of prices) { if (price === 0) continue; if (price > 1000) break; total += price; console.log("Added", price);} console.log("Total:", total);Output
> Added 120> Added 450> Total: 5704.8 Comparison: which loop when
| Construct | Use when | Watch out |
|---|---|---|
| if / else if / else | Range checks, different conditions | Specific condition first |
| switch | One value vs many fixed values | break in every case + default |
| for | You know the count | Off-by-one in the condition |
| while | You don't know the count (retries) | Update the variable or it loops forever |
| for...of | Values of an array / string / Map | No index unless you add one |
| for...in | Keys of an object | Keys are strings; avoid for arrays |
4.9 Common mistakes
- Forgetting break in a switch: after "placed" matches, the cases below also run (fall through), printing 3 lines.
- Fix: put break at the end of every case.
- break inside forEach is a SyntaxError and return only skips one item; to exit early use for...of (or find).
- Forgetting to update the condition variable in a while loop.
JavaScript
// Wrongconst status = "placed"; switch (status) { case "placed": console.log("Order confirmed"); case "shipped": console.log("On the way"); default: console.log("Unknown status");}JavaScript
// Rightconst status = "placed"; switch (status) { case "placed": console.log("Order confirmed"); break; case "shipped": console.log("On the way"); break; default: console.log("Unknown status");}4.10 Interview tips
- for...of gives the values of any iterable (array, string, Map).
- for...in gives the enumerable keys of an object, always as strings, and can pick up inherited properties; prefer for...of for arrays.
- break does not work in forEach; for an early exit use for...of with break.
- switch uses strict equality, and a missing break causes fall through.