DEV Community

Juan Garcia
Juan Garcia

Posted 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 === 3) {
      console.log('user1 is winner');
    } else if (user2 === 3) {
      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);

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay