Funktion
Funktion

Reputation: 559

Loop in JavaScript until a condition is met

I'm trying to loop indefinitely until a condition is met...is the following correct?

It seems not to be.

    var set = false;
    while(set !== true) {
        var check = searchArray(checkResult, number);
        if(check === false) {
            grid.push(number);
            set = true;
        } 
    }

Upvotes: 20

Views: 98725

Answers (3)

Iblob
Iblob

Reputation: 150

Let's go over this. You want the code to loop until the function searcharray() returns true, right?

First, the code creates the variable "set" and sets it to false.

Then while set is not equal to true (would suggest using triple equals here), run this code:

Create the variable "check" and set it to what searcharray returns.

If searcharray returns false, it will add a number on to the end of the array grid as a new entry and then set "set" to true.

Then it loops again. If searcharray returned true, it loops again as set is still false. If search array returned false, it does not loop again and skips to the end.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386604

Basically, you can make an infinite loop with this pattern and add a break condition anywhere in the loop with the statement break:

while (true) {
    // ...
    if (breakCondition) {            
        break;
    } 
}

Upvotes: 44

MobileX
MobileX

Reputation: 419

The code will loop while searchArray result is not false and until it becomes false. So the code is correct if you wanted to achieve such behavior and it's not correct otherwise.

Upvotes: 1

Related Questions