DEV Community

Juan Garcia
Juan Garcia

Posted on • Edited on

While Loops

You can think of a while loop as a board game that goes on an indefinite amount of times until a winner is found, We have a clear vision of what we need to do to win the game but we're not sure of how long it will take since its dependant on outside factors like chance, number of people playing the game.

Check out this example:

let user1 = 0;
let user2 = 0;
let winScore = 3;
while(user1 < winScore && user2 < winScore) {
    let dice1 = Math.random()
    let dice2 = Math.random()
    if (dice1 > dice2) {
      user1 += 1;
    } else if (dice2 > dice1)  {
      user2 += 1;
    }
    if (user1 === winScore) {
      console.log('user1 is winner');
    } else if (user2 === winScore) {
      console.log('user2 is winner');
    }
};

Enter fullscreen mode Exit fullscreen mode

The syntax of a while loop is pretty straightforward, While a condition is true or false we want to execute a piece of code. The condition is always placed inside parentheses right after the while keyword, and as long as that condition is met we're running a piece of code that in most cases, to not create infinite loops we want that piece of code inside of the loop to modify the variables being evaluated in the condition. (the block of code after the while loop statement goes in between a pair of curly braces);

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series