Techoceanhub logo

Loops (for, while, do-while) in Javascript

For Loop:

The for loop is used when you know beforehand how many times you want to iterate.

// Example of a for loop
for (let i = 0; i < 5; i++) {
    console.log(i); // Outputs 0, 1, 2, 3, 4
}

While Loop:

The while loop is used when you want to execute a block of code as long as a condition is true. It’s suitable when you don’t know how many times you’ll iterate beforehand.

// Example of a while loop
let j = 0;
while (j < 5) {
    console.log(j); // Outputs 0, 1, 2, 3, 4
    j++;
}

Do-While Loop:

The do-while loop is similar to a while loop, but it ensures that the block of code executes at least once before checking the condition.

// Example of a do-while loop
let k = 0;
do {
    console.log(k); // Outputs 0, 1, 2, 3, 4
    k++;
} while (k < 5);

In each example:

  • The for loop initializes a variable (i), checks a condition (i < 5), executes a block of code (console.log(i)), and increments (i++) after each iteration.
  • The while loop checks a condition (j < 5), executes a block of code (console.log(j)), and increments (j++) inside the loop.
  • The do-while loop executes the block of code (console.log(k)), increments (k++), and then checks the condition (k < 5).

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .