Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Create a for Loop

Ivana Lescesen
Ivana Lescesen
19,442 Points

What are the differences between the loops?

Hello amazing people of Treehouse, would anyone be so kind to explain the difference between the loops in javascript and compare them. Thank you so much :)

3 Answers

The while loop is usually used when you need to repeat something until a given condition is true:

inputInvalid = true;
while(inputInvalid)
{
    //ask user for input
    invalidInput = checkValidInput();
}

On the other hand, the for loop is usually used when you need to iterate a given number of times:

for(var i = 0; i < 100; i++)
{
    ...//do something for a 100 times.
}

You can use them interchangeably if you like:

inputInvalid = true;
for(;;)
{
    if(!inputInvalid)
    {
        break;
    }
    //ask user for input
    invalidInput = checkValidInput();
}

Or

inputInvalid = true;
for(;inputInvalid;)
{        
    //ask user for input
    invalidInput = checkValidInput();
}

And:

var i = 0;
while(i < 100)
{
    //do your logic here
    i++;
}

Credits - npinti, from StackExchange.

I hope this helps.

Ivana Lescesen
Ivana Lescesen
19,442 Points

Thank you so much, what about the do while loop?

do while checks the conditional after the block is run. while checks the conditional before it is run. This is usually used in situations where the code is always run at least once.