How to use while and for loop in JavaScript

 

In JavaScript, the while loop and for loop work similarly to their Python counterparts. Here are examples of how to use while loop and for loop in JavaScript:

While Loop:

The while loop in JavaScript executes a block of code repeatedly as long as a given condition is true. Here's an example of a while loop in JavaScript:

css

// Example 1: while loop let i = 1; while (i <= 5) { console.log(i); i = i + 1; }

In this example, the while loop will continue to execute as long as the value of i is less than or equal to 5. Each time the loop executes, the value of i is logged to the console, and then the value of i is incremented by 1. The loop will terminate when the value of i becomes 6.

For Loop:

The for loop in JavaScript is used for iterating over a sequence (that is either an array or a string). Here's an example of a for loop in JavaScript:

css

// Example 2: for loop const fruits = ['apple', 'banana', 'cherry']; for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); }

In this example, the for loop iterates over an array of fruits and logs each fruit to the console. The loop will terminate once it has iterated over all the elements in the array.

Nested Loops:

Nested loops in JavaScript work similarly to nested loops in Python. Here's an example of a nested for loop in JavaScript:

javascript

// Example 3: nested for loop for (let i = 1; i <= 3; i++) { for (let j = 1; j <= 3; j++) { console.log(i, j); } }

In this example, the outer loop iterates over the values 1, 2, and 3. For each value of the outer loop, the inner loop iterates over the values 1, 2, and 3. The loop logs each combination of i and j to the console. The loop will terminate once it has iterated over all combinations of i and j.

0 Comments

You can use the contact form below to send us a message

We would love to hear from you! If you have any questions, comments, or suggestions, please feel free to get in touch with us.