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

Greg Schudel
Greg Schudel
4,090 Points

for loop vs while loop

What is the difference between using a regular while loop and a for loop? they seem similar....please list pro and cons

1 Answer

codeoverload
codeoverload
24,260 Points

Use a for loop if you know how often you want to run the loop.
Use a while loop if you don't know how often you want to run the loop and if it depends on a specific condition.
Example:

var userInput = "";
// You don't how many guesses the user needs
while (userInput != "4") {
  userInput = prompt("Guess the secret number: ");
}

// But you do know how often you want to print "That was correct!"
for (var i = 0; i < 3; i++) {
  alert("That was correct!");
}

Hope this helps! (But for the next time: consider asking google first, if it's such a basic question ;))