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

Updated 25 Sep 20265 min read

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?"

js
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.

js
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

js
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.

js
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

js
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); // Weekend

switch uses strict case matching. Cases can share a result, but an omitted break may fall through.

js
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

js
let total = 0;
for (let i = 1; i <= 5; i++) total += i;
console.log(total); // 15

Use for for a task counter and while for a changing condition:

js
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:

js
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:

js
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

js
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}`);
Code
72: first class
48: pass
91: distinction
66: first class
39: fail
Passed: 4, Failed: 1, Average: 63.2

Here, 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.

Loop-state trace table for the scores 72, 48, 91, 66 and 39, showing the running total, chosen grade and pass count at each iteration.
Flowchart of the grade decision in one iteration: below 40 fails, 75 and above is distinction, 60 and above is first class, otherwise pass.

break, continue and Nested Loops Without Losing Control

continue skips the rest of the current iteration. break exits the loop:

js
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); // 14

It skips 3, 8, and 11, selects 14, and never inspects 18.

Nested loops pair every outer value with every inner value:

js
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

i <= values.length with [10, 20, 30]

Visits index 3 and reads undefined

Use i < values.length

while (count < 3) without count++

Never terminates

Update the condition variable

if (score = 0)

Assigns 0 and takes the false branch

Compare with score === 0

Missing break after case 7

The default block also runs and overwrites dayType with Invalid day

Add break unless fall-through is deliberate

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:

  1. Put narrow branches before broad ones.

  2. Use switch only for discrete matches.

  3. Choose a loop whose stopping condition is visible.

  4. Update every variable used to control a while loop.

  5. Trace break and continue before 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.