JavaScript loop & Switch

Why should you care about JavaScript Loops and Switch?

Loops and switch statements help you write less code and handle repeated or branching logic cleanly. They are core tools in almost every real project.

Loops repeat code without requiring the same statements again and again. Three repeated calls are easy to write, but a loop scales when the amount of work changes.

javascript

console.log("Hello");
console.log("Hello");
console.log("Hello");

for (let i = 0; i < 3; i++) {
  console.log("Hello");
}

switch is different from loops: it chooses one branch from several exact possible values.

A loop repeatedly executes a block while a condition or iteration rule allows it to continue. One execution of the loop body is an iteration.

javascript

for (let i = 0; i < 3; i++) {
  console.log(i);
}
// Iterations: i = 0, i = 1, i = 2
// Stop when i = 3
for loop

A for loop puts initialization, condition, and update in one place.

javascript

for (initialization; condition; update) {
  // code to execute
}

for (let i = 0; i < 10; i++) {
  console.log(i);
}
  • Initialization: runs once before the first iteration.
  • Condition: is checked before every iteration; false stops the loop.
  • Update: runs after each iteration and moves the loop toward stopping.

for...of iterates over values produced by an iterable. Arrays and strings are common examples.

javascript

const numbers = [1, 2, 3, 4, 5];
for (const number of numbers) {
  console.log(number);
}

for (const character of "JavaScript") {
  console.log(character);
}

variable receives the current value; iterable is the collection or sequence being visited.

Choose based on what the loop needs.
NeedRecommended
Each value from an arrayfor...of
The array indexfor
Custom increments or backwards iterationfor
Simple value iterationfor...of

javascript

const fruits = ["Apple", "Banana", "Mango"];
for (const fruit of fruits) console.log(fruit);

for (let i = 0; i < fruits.length; i++) {
  console.log(i, fruits[i]);
}
while loop

Use while when repetition depends mainly on a condition rather than a predefined counter. The condition is checked before each iteration, so the loop may run zero times.

javascript

let i = 0;
while (i < 10) {
  console.log(i);
  i++;
}
do while loop

do...while runs the body at least once because it checks the condition after the body.

javascript

let i = 0;
do {
  console.log(i);
  i++;
} while (i < 10);

let count = 10;
do {
  console.log("This runs once");
} while (count < 5);

while may run zero times; do...while runs at least once.

for...in iterates over enumerable property keys.

javascript

const user = {
  name: "Aarav",
  age: 21,
  city: "Jaipur"
};
for (const key in user) {
  console.log(key, user[key]);
}
// name Aarav, age 21, city Jaipur

for...of gives values; for...in gives keys. For arrays, prefer for...of for values. for...in can also include inherited enumerable properties.

break immediately exits the nearest enclosing loop. In a switch, it exits the switch statement.

javascript

for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i); // 0 1 2 3 4
}

continue skips the remaining statements in the current iteration of the nearest enclosing loop and proceeds to the next iteration.

javascript

for (let i = 1; i <= 5; i++) {
  if (i === 3) continue;
  console.log(i); // 1 2 4 5
}

break exits completely; continue skips only the current iteration.

A nested loop is a loop inside another loop. For every iteration of the outer loop, the inner loop completes all of its iterations.

javascript

const grid = [
  ["A1", "A2"],
  ["B1", "B2"]
];
for (const row of grid) {
  for (const cell of row) {
    console.log(cell);
  }
}

Nested loops fit multidimensional data such as rows and columns. If the outer and inner loops each run three times, the inner body can run nine times. Avoid unnecessary nesting because it makes code harder to understand and increases the work.

switch statement

A switch compares one expression against several exact case values. Matching uses strict comparison semantics.

javascript

const day = "Monday";
switch (day) {
  case "Monday":
    console.log("Today is Monday.");
    break;
  case "Tuesday":
    console.log("Today is Tuesday.");
    break;
  default:
    console.log("Another day.");
}

switch evaluates the expression, checks cases, runs the match, and uses break to exit. default runs when no case matches.

Choose the clearer branching structure.
SituationUsually clearer
One value and several exact valuesswitch
Complex conditions or rangesif...else
Conditions using && or ||if...else
Fixed states such as loading/success/errorswitch

javascript

const status = "success";
switch (status) {
  case "loading": console.log("Loading..."); break;
  case "success": console.log("Success!"); break;
  case "error": console.log("Something went wrong."); break;
  default: console.log("Unknown status.");
}

Without break, JavaScript continues into following cases until it reaches a break or the end. This can intentionally group cases, but accidental fall-through can surprise readers.

javascript

const grade = "A";
switch (grade) {
  case "A":
  case "B":
    console.log("Passing grade");
    break;
  default:
    console.log("Other grade");
}

default runs when none of the cases match.

javascript

const status = "unknown";
switch (status) {
  case "success": console.log("Success"); break;
  case "error": console.log("Error"); break;
  default: console.log("Unknown status");
}
Final loop and branching decision guide.
QuestionUseExample
Need an index or custom counter?forEvery second item
Need each iterable value?for...ofRead product names
Need object property keys?for...inInspect object properties
Repetition depends on a condition?whileRead until a queue is empty.
Must run once first?do...whileShow a menu
Need exact value matching?switchHandle success/error/loading

for means counter/index; for...of means values; for...in means keys; while means condition-controlled repetition; do...while means run once then check; switch means exact values.

A loop becomes infinite when its stopping condition never becomes false.

javascript

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

// Without i++, the condition never changes.
// Do not run that version in an interactive playground.
  • What starts the loop?
  • What condition stops it?
  • What changes on every iteration?
  • Can the condition become false?
  • Forgetting to update a while loop variable.
  • Using for...in for array values instead of for...of.
  • Forgetting break in a switch when fall-through is not intended.
  • Forcing every problem into a classic for loop.
  • Using excessive nested loops when the data does not have multiple dimensions.
  • for → control the counter or index.
  • for...of → receive each value.
  • for...in → receive each enumerable key.
  • while → continue while a condition is true.
  • do...while → run once, then check.
  • break → stop the nearest loop or switch.
  • continue → skip the current iteration.
  • switch → choose based on exact values.

Keep practicing from simple repetition to nested patterns.

Beginner

  • Print numbers from 1 to 10.
  • Print even numbers and calculate a sum.
  • Iterate over an array with for...of and an object with for...in.
  • Write a while and a do...while loop.

Control Flow

  • Use break and continue.
  • Write a switch with a default case.
  • Demonstrate intentional fall-through.

Nested Loops

Retain the existing interactive pattern practice: square, right triangle, inverted triangle, hollow rectangle, number pyramid, and diamond. Use the existing “View example pattern” controls to compare your output.

  • for controls initialization, condition, and update.
  • for...of iterates values; for...in iterates enumerable keys.
  • while repeats while a condition is truthy; do...while runs at least once.
  • Nested loops fit multidimensional data.
  • switch handles exact value matching.
  • break exits the nearest loop or switch; continue skips the current iteration.
  • Infinite loops happen when the stopping condition never becomes false.
What's next? Now that you know how to repeat code and control program flow, learn how JavaScript works with text in Strings.
JavaScript loops and switch lecture in Hindi
SimplyJavaScript Logo
loop and Switch In Javascript
JavaScript loops and switch lecture in English
SimplyJavaScript Logo
loop and Switch In Javascript

Reviewed by

SimplyJavaScript Editorial Team

Technical editors and JavaScript educators with hands-on experience building frontend projects, writing learning material, and reviewing tutorials for clarity, accuracy, and beginner-friendly guidance.