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 let you repeat code without copying the same lines again and again. If you need to process a list or run a task many times, loops make it short and clean.

The for loop is best when you know how many times you want to repeat something. It has three parts in one line:

for-loop

javascript

for (initialization; condition; increment/decrement) {
  // code to be executed
} 

Here is how each part works:

  • Initialization: It kicks things off by setting up a variable, usually a counter. This runs only once at the beginning.
  • Condition: This is checked before each iteration. If true, the loop continues. If false, the loop stops.
  • Increment/Decrement: This updates the counter after each run and moves the loop toward stopping.

javascript

for (var i = 0; i < 10; i++) {
  console.log(i);
} 

The for...of loop is the easiest way to go through each item in an array, a string, or any other iterable. You don't need a counter variable or index:

javascript

//Syntax
for (variable of iterable) {
  // code to be executed
}

//Example:                
let array = [1, 2, 3, 4, 5];
for (const item of array) {
  console.log(item);
} 
  • variable: It represents the current item in the iteration. You assign this variable to hold the value of each item in the iterable as you loop through.
  • iterable: This refers to the array, string, or any iterable object you want to loop through.

My take: for...of is my go-to loop for arrays and most iterables. It is cleaner than the classic for (let i = 0; ...) because you do not have to manage an index, and unlike .forEach(), you can use break, continue, and return inside it. The traditional for loop still has its place - when you need the index for logic (not just logging), or when you are iterating backwards. But if you just need each item, for...of is the most readable choice. And a word on for...in: only use it for objects. Using for...in on arrays is a classic bug source because it iterates over all enumerable properties, not just numeric indices.

The for...in loop is designed for objects. Instead of giving you values, it gives you the keys (property names) of an object one at a time:

javascript

// Syntax
for (const key in object) {
  // code to be executed
}

// Example
const user = { name: "Aarav", age: 21, city: "Jaipur" };
for (const key in user) {
  console.log(key, user[key]);
} 
  • key: Represents the current property name in each iteration.
  • object: The object whose enumerable properties you want to iterate over.

A while loop keeps running as long as its condition is true. Unlike a for loop, you manage the counter yourself:

while-loop

javascript

//Syntax
while (condition) {
  // code to be executed
}

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

The do...while loop is similar to while, but with one important difference: the loop body runs at least once before the condition is checked.

do-while-loop

javascript

//Syntax
do {
  // code to be executed
} while (condition);

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

The block inside do runs first. After that, JavaScript checks the while condition to decide whether to continue.

A nested loop is a loop inside another loop. Every time the outer loop runs once, the inner loop runs all the way through. For example, if the outer loop runs 3 times and the inner loop runs 3 times, the code inside runs 9 times total.

javascript

for (let row = 1; row <= numRows; row++) {
  // Draw a row (outer loop)
  for (let column = 1; column <= numColumns; column++) {
    // Draw a square in the row (inner loop)
    // Draw the square at the current row and column
  }
} 

Tip: Use for...of for arrays and other iterables. Use for...in for object keys.

A switch statement checks a value against a list of possible matches and runs the code for whichever one matches. It's a cleaner alternative to writing many if...else if blocks:

switch

javascript

switch (expression) {
  case value1:
    // code to be executed if expression === value1
    break;
  case value2:
    // code to be executed if expression === value2
    break;
  ...
  default:
    // code to be executed if expression does not match any of the cases
} 

Here is an example that checks the value of day and prints a matching message:

javascript

let day = "Monday";
switch (day) {
  case "Monday":
    console.log("Today is Monday.");
    break;
  case "Tuesday":
    console.log("Today is Tuesday.");
    break;
  case "Wednesday":
    console.log("Today is Wednesday.");
    break;
  case "Thursday":
    console.log("Today is Thursday.");
    break;
  case "Friday":
    console.log("Today is Friday.");
    break;
  default:
    console.log("Today is a weekend day.");
} 

Always include a break after each case, otherwise JavaScript will keep running the next case even if it doesn't match (this is called "falling through"). The default case at the end handles anything that doesn't match.

Switch works best when you're comparing a single value against a list of exact matches. For ranges or complex conditions, if...else is usually a better fit.

The break keyword immediately exits a loop or switch statement. Once JavaScript hits a break, it stops the current loop and moves on to the code after it.

javascript

let grade = 'B';
switch (grade) {
  case 'A':
    console.log("Excellent");
    break;
  case 'B':
    console.log("Good");
    break;
  default:
    console.log("Invalid grade");
} 

for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break; // Exit the loop when i is 5
    }
    console.log(i); // Output: 0, 1, 2, 3, 4
}
console.log('Loop has been exited.');

In this loop, JavaScript stops at i === 5, so only 0 to 4 are printed.

  • for is great when you know iteration count in advance.
  • for...of iterates values from arrays and other iterables.
  • for...in iterates keys of objects.
  • while and do...while are useful when repetition depends on a condition.
  • switch is cleaner than long if-else chains for exact value matching.
  • break exits loops or switch blocks immediately.

What's next? Continue to Strings to work with text values in JavaScript.

lecture javascript
SimplyJavaScript Logo
Loop & Switch In Javascript
lecture javascript
SimplyJavaScript Logo
Loop & 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.