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

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 ;))