🟨 JavaScript tutorial for beginners · Class 8 · Lesson 9 of 18 · Free
Conditional Logic & Loops in JavaScript – if, else, for and while
⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in
In this lesson you will
- Make decisions with if, else if, else, && and ||
- Repeat code a fixed number of times with a for loop
- Repeat until something changes with a while loop, and stop early with break
A railway ticket costs half for children under 12 and full for everyone else. A program must DECIDE which price to show. And to print the 7 times table, it must REPEAT a line 10 times. Decisions and repeats are what make code smart.
How does if / else work in JavaScript?
if checks a condition in round brackets. If it is true, the code in the curly braces runs. If it is false, the else part runs instead.
Conditions use comparisons: > (more than), < (less than), >= , <= , === (equal) and !== (not equal).
Change age to 30 and run again. Only one of the two messages can ever print.
▶const age = 10;2const fullFare = 400;3let fare;4if (age < 12) {5 fare = fullFare / 2;6 console.log("Child ticket");7} else {8 fare = fullFare;9 console.log("Adult ticket");10}11console.log(`Fare: ₹${fare}`);
No variables yet.
▌✏️ Change this code and run it yourself
Child ticketFare: ₹200
How do I check many conditions with else if?
When there are more than two choices, chain else if. JavaScript checks from the top and stops at the FIRST true condition.
So the order matters: put the highest grade first. If you checked >= 35 first, a 95 would get "Pass"!
&& means AND (both must be true). || means OR (at least one must be true).
▶const marks = 82;2if (marks >= 90) {3 console.log("Grade A+");4} else if (marks >= 75) {5 console.log("Grade A");6} else if (marks >= 35) {7 console.log("Pass");8} else {9 console.log("Try again");10}11const attendance = 80;12console.log("Can sit for exam:", marks >= 35 && attendance >= 75);13const day = "Sunday";14console.log("Holiday:", day === "Saturday" || day === "Sunday");
No variables yet.
▌✏️ Change this code and run it yourself
Grade ACan sit for exam: trueHoliday: true
💡 Try it: set marks to 95, then 40, then 20. Which line prints each time?
How does a for loop work in JavaScript?
A for loop has three parts in its brackets, separated by semicolons: where to start, when to keep going, and what to change after each round.
for (let i = 1; i <= 5; i++) means: start i at 1, run while i is 5 or less, add 1 to i after each round. i++ is short for i = i + 1.
Watch the trace: i goes 1, 2, 3, 4, 5, and then the check i <= 5 becomes false, so the loop ends.
▶const n = 7;2for (let i = 1; i <= 5; i++) {3 console.log(`${n} x ${i} = ${n * i}`);4}5console.log("Done!");
No variables yet.
▌✏️ Change this code and run it yourself
7 x 1 = 77 x 2 = 147 x 3 = 217 x 4 = 287 x 5 = 35Done!
💡 Try it: change 5 to 10 for the full table, or n to 13.
How does a while loop work in JavaScript?
A while loop repeats as long as its condition is true. Use it when you do not know in advance how many rounds you need.
Here you save ₹150 every week. How many weeks until you have ₹500 for a cricket bat? The loop finds out.
Always change something inside the loop. If the condition never becomes false, the loop never ends (an infinite loop).
Week 1: ₹150Week 2: ₹300Week 3: ₹450Week 4: ₹600Bat bought after 4 weeks!
How do I use if inside a loop, with break and continue?
Loops and if work best together: the loop visits every item, and if decides what to do with each one.
continue skips the rest of this round and jumps to the next item. break stops the whole loop at once.
Here: skip absent students (marked -1), and stop as soon as we find a perfect 100.
Absent, skipFound a 100! Stop.Passed before stopping: 2
How do I use if/else on a web page with JavaScript?
Now the decision comes from the user. Type any marks and click the button. The page shows the grade with a colour.
Input boxes always give text, so Number() turns it into a number before we compare.
📄 HTML of the page (tap to see / edit)
78 → A
💡 A ? B : C is a short if/else: if A is true use B, else use C. When an if has only one line, you may leave out the braces.
🤔 Predict the output
Think like JavaScript: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
const score = 85;
if (score >= 50) {
console.log("C");
} else if (score >= 80) {
console.log("A");
} else {
console.log("Fail");
}Question 2. What does this print?
for (let i = 1; i <= 3; i++) {
console.log(i * 2);
}Question 3. What does this print?
let n = 10;
while (n > 3) {
n = n - 3;
}
console.log(n);🧩 Your challenge
Diwali lights! Number the lamps 1 to 15. For a multiple of both 3 and 5, print "✨ sparkle". For only a multiple of 3, print "🪔 diya". For only a multiple of 5, print "🎆 rocket". Otherwise print the number. The first lines should be: 1 2 🪔 diya 4 🎆 rocket 🪔 diya … and the last line is ✨ sparkle (for 15).
1 2 🪔 diya 4 🎆 rocket 🪔 diya 7 8 🪔 diya 🎆 rocket 11 🪔 diya 13 14 ✨ sparkle
⚠️ Common mistakes (and how to fix them)
❌ Wrong
let marks = 45;
if (marks = 100) {
console.log("Full marks!");
}No error — but it prints "Full marks!" for 45, because marks = 100 changes marks to 100, which counts as true.
✅ Right
let marks = 45;
if (marks === 100) {
console.log("Full marks!");
}= puts a value into a variable. === compares. Inside if, you almost always want ===.
❌ Wrong
const names = ["Asha", "Ravi", "Meera"];
for (let i = 0; i <= names.length; i++) {
console.log(names[i]);
}No error — but a fourth line "undefined" appears, because the loop also visits index 3, which does not exist.
✅ Right
const names = ["Asha", "Ravi", "Meera"];
for (let i = 0; i < names.length; i++) {
console.log(names[i]);
}The last index is length − 1. Use < length, not <= length.
❌ Wrong
let count = 0;
while (count < 3) {
console.log("Count:", count);
}Error: This loop ran for too long — it may never stop. Check the loop condition.
✅ Right
let count = 0;
while (count < 3) {
console.log("Count:", count);
count++;
}Nothing inside the loop changes count, so count < 3 stays true for ever. Always move the loop towards its end.
📌 Remember
- if (condition) { … } else { … } runs only one of the two blocks.
- else if checks from the top and stops at the first true one — order matters.
- && = both true, || = at least one true; compare with ===, not =.
- for (let i = 1; i <= 5; i++) repeats a fixed number of times.
- while repeats until the condition is false — make sure it changes!
- continue skips one round; break stops the loop.
Finished the quiz and the challenge?
Questions students ask
What is the difference between for and while loops in JavaScript?
Use for when you know how many rounds you need, like 1 to 10. Use while when you repeat until something happens, like saving until you reach ₹500. Both can do the same job.
What is the difference between = , == and === in JavaScript?
= stores a value. === checks if two values are equal AND of the same type. == also compares but first converts types, so "5" == 5 is true. Beginners should use === always.
What happens if my loop never stops?
That is an infinite loop. The page can freeze. On this page, the runner stops long loops for you. Fix it by making sure the condition becomes false, for example by adding count++.
What does i++ mean in JavaScript?
It adds 1 to i. It is a short way of writing i = i + 1. Similarly, i-- takes away 1.