Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.