JavaScript Loop & Switch

Loops let you run the same code over and over without writing it out each time. If you need to process a list of items or repeat a task 100 times, a loop handles it for you in just a few lines.

The for loop is perfect when you know exactly how many times you want to repeat something. It has three parts all on one line:

for-loop

javascript

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

Here's a breakdown of how it works:

  • Initialization: It kicks things off by setting up, usually initializing a counter variable. This part happens once at the beginning of the loop.
  • Condition: On each run through the loop, this condition gets checked. If it's true, the code block inside the loop runs. If false, the loop stops.
  • Increment/Decrement: After each loop iteration, this step happens. It's often used to update the counter variable, shifting it closer to the condition being false.

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.

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

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 in JavaScript is a lot like the while loop, but with a twist. It ensures that the code inside the loop runs at least once, even if the condition initially evaluates to false. Here's how it's structured:

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 of code inside the do runs first, unconditionally, before the condition is even checked. After the code runs for the first time, the while condition is evaluated.

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
  }
} 

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 of a switch statement that checks the value of a variable called day and outputs a message depending on the day:

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.');

The for loop iterates from 0 to 9, but the break statement exits the loop when i is 5, so it only prints numbers 0 through 4.

lecture javascript
SimplyJavaScript Logo
Loop & Switch In Javascript
lecture javascript
SimplyJavaScript Logo
Loop & Switch In Javascript