While Loops

Patricia Arquette
Patricia ArquetteOriginal
2024-12-06 16:15:16919browse

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

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

The above is the detailed content of While Loops. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn