JavaScript Conditionals and Loops: Beginner Tutorial with Runnable Examples
Learn how JavaScript chooses a branch and repeats work. Build from small syntax examples to a complete score classifier with a traced average.
KnowledgeGate Team
Exam prep & CS education

You may write one JavaScript statement comfortably, then get stuck when a program must choose a path or repeat work. Suppose you need to classify five scores and calculate their average. Copying the logic five times is error-prone. JavaScript uses if, else if, switch, for, while, do...while, break, and continue to choose paths and repeat work, and a runnable program can be traced line by line.
Conditionals Choose a Path and Loops Repeat a Step
A conditional answers, "Which block runs?" A loop answers, "How many times?"
const temperature = 32;
if (temperature >= 30) {
console.log("Hot day");
}Braces mark the controlled block in top-to-bottom execution. Since 32 >= 30 is true, it alone runs and prints Hot day.
for (let round = 1; round <= 3; round++) {
console.log(`Round ${round}`);
}round starts at 1. The loop tests round <= 3 before each iteration and adds 1 after the body. It prints Round 1, Round 2, and Round 3. A loop can pass each score to a conditional that chooses its label.
if, else if and else: Order the Conditions Carefully
const score = 72;
const attendance = 81;
if (score >= 40 && attendance >= 75) {
console.log("Eligible");
}Both comparisons are true, so true && true prints Eligible. With attendance 68, 68 >= 75 makes the condition false.
const score = 72;
if (score >= 75) {
console.log("Distinction");
} else if (score >= 60) {
console.log("First class");
} else if (score >= 40) {
console.log("Pass");
} else {
console.log("Fail");
}For 72, the second test is the first match and prints First class. Only that branch runs, so put score >= 75 before score >= 40.
Prefer strict comparison, such as status === "active". The non-empty string "0" is truthy, but numeric 0 is falsy. Convert numeric text explicitly at the input boundary.
switch and the Ternary Operator for Focused Choices
const dayNumber = 6;
let dayType;
switch (dayNumber) {
case 1:
case 2:
case 3:
case 4:
case 5:
dayType = "Weekday";
break;
case 6:
case 7:
dayType = "Weekend";
break;
default:
dayType = "Invalid day";
}
console.log(dayType); // Weekendswitch uses strict case matching. Cases can share a result, but an omitted break may fall through.
const score = 72;
const result = score >= 40 ? "Pass" : "Fail";result is Pass. Use if for ranges or compound logic, switch for discrete matches, and a ternary for one short two-way choice. Keep grade ladders as if...else if...else, not nested ternaries.
for, while, do...while and for...of
let total = 0;
for (let i = 1; i <= 5; i++) total += i;
console.log(total); // 15Use for for a task counter and while for a changing condition:
let count = 3;
while (count > 0) {
console.log(count);
count--;
}
console.log("Start");This prints 3, 2, 1, then Start. A do...while runs at least once:
let attempts = 0;
do {
attempts++;
console.log(`Attempt ${attempts}`);
} while (attempts < 1);It prints Attempt 1, although the condition is then false. Use for...of for iterable values:
for (const score of [72, 48, 91]) {
console.log(score);
}It visits 72, 48, and 91 in order. for...of gives values; for...in gives property keys. Avoid for...in for array values.
Worked Example: Classify Five Scores and Calculate the Average
const scores = [72, 48, 91, 66, 39];
let passed = 0;
let total = 0;
for (const score of scores) {
total += score;
if (score < 40) {
console.log(`${score}: fail`);
continue;
}
passed++;
if (score >= 75) {
console.log(`${score}: distinction`);
} else if (score >= 60) {
console.log(`${score}: first class`);
} else {
console.log(`${score}: pass`);
}
}
const failed = scores.length - passed;
const average = total / scores.length;
console.log(`Passed: ${passed}, Failed: ${failed}, Average: ${average}`);72: first class
48: pass
91: distinction
66: first class
39: fail
Passed: 4, Failed: 1, Average: 63.2Here, 72 + 48 + 91 + 66 + 39 = 316, and 316 / 5 = 63.2. Four scores are at least 40; one is below 40.
total includes 39. For 39, continue skips passed++ and the grade chain only for that iteration. Passing scores increment passed before grading.


break, continue and Nested Loops Without Losing Control
continue skips the rest of the current iteration. break exits the loop:
const values = [3, 8, 11, 14, 18];
let answer;
for (const value of values) {
if (value <= 10 || value % 2 !== 0) continue;
answer = value;
break;
}
console.log(answer); // 14It skips 3, 8, and 11, selects 14, and never inspects 18.
Nested loops pair every outer value with every inner value:
for (let row = 1; row <= 2; row++) {
for (let seat = 1; seat <= 3; seat++) {
console.log(`R${row}S${seat}`);
}
}The inner loop completes for each outer value. Rows 1 and 2 with seats 1 to 3 produce R1S1, R1S2, R1S3, R2S1, R2S2, R2S3. The body runs 2 * 3 = 6 times. An unlabelled break exits only the nearest loop. To leave several levels, use a function and return.
Common Errors, Output Tracing and Practice Checks
Error | Exact symptom | Fix |
|---|---|---|
| Visits index 3 and reads | Use |
| Never terminates | Update the condition variable |
| Assigns 0 and takes the false branch | Compare with |
Missing | The | Add |
Practise output prediction, iteration counts, first matches, infinite-loop repairs, and jump tracing. Three checks: summing 1 through 5 gives 15; the first even value above 10 in [3, 8, 11, 14, 18] is 14; value > 0 matches 2 values in [5, -2, 0, 7, -1].
Use Infosys Pseudocode Questions for manual tracing, then try Classic Programs in C, Java and Python for cross-language loops. Syntax differs across C, Java, Python and JavaScript, especially around iterable loops and truthy conditions.
JavaScript Conditionals and Loops: Short Version and Next Step
Keep five rules in view:
Put narrow branches before broad ones.
Use
switchonly for discrete matches.Choose a loop whose stopping condition is visible.
Update every variable used to control a
whileloop.Trace
breakandcontinuebefore running the code.
The worked total is 316, the average is 63.2, four scores pass, and one fails.
Append 75 to scores. Predict 75: distinction, total 391, passed 5, failed 1, and raw JavaScript average 391 / 6 = 65.16666666666667. Displaying 65.17 to two decimal places changes the formatting, not the stored value.
Continue with the Complete JavaScript Course. Later, apply JavaScript to full-stack work through the MERN Stack Course. Browse Coding & Skill Development Courses for the wider course hub.
Keep learning

JavaScript Event Delegation: Bubbling, target and currentTarget with Runnable Examples
Learn how browser events travel through the DOM, then build one delegated listener that handles nested controls and rows added later.

JavaScript Operators: Types, Precedence and Runnable Examples
Learn how JavaScript arithmetic, assignment, comparison, logical and modern operators behave by tracing one score program from inputs to final output.

JavaScript Data Types and Coercion: Beginner Tutorial with Runnable Examples
Learn how JavaScript stores values, copies primitives and objects, converts input, compares values and produces surprising output. Trace each rule in the console.

Mongoose Validation: Enforce Schema Invariants and Avoid Update Traps
Trace one Plan model through saves, query updates and database errors. The worked cases show exactly where Mongoose rules hold and where an update can bypass them.