skip to Main Content

I’m trying to write a code where if a randomly generated number matches one of the numbers in for loop it should output "True" if not then false.

let min = 20;let max = 50;

let a = (Math.floor(Math.random() * (max - min)) + min);

for (let i=0; i<30; i++){
    if (i == a){
        console.log("True");
        break;
    }
    else{
        console.log("False");
    }
}

It ends up spamming false until the point it reaches the condition. Is there a way I can prevent this?

2

Answers


  1. If I correctly understand, the best thing to do (well, a good thing at least) is to take the logging out of the loop entirely:

    let min = 20;let max = 50;
    
    let a = (Math.floor(Math.random() * (max - min)) + min);
    let message = "False";
    for (let i=0; i<30; i++){
        if (i == a){
            message = "True";
            break;
        }
    }
    console.log(message);
    

    And you could do that with a couple of different approaches, but the basic idea is that your code remembers what happened in the loop, and then reports that after the loop is finished.

    Login or Signup to reply.
  2. it’s generate a random number between 20 – 50 ,

    but your loop is stop at 30 ,
    you might fix it by edit your loop end point to 50

    for (let i=0; i<=50; i++){
        if (i == a){
            console.log("True");
            break;
        }
        else{
            console.log("False");
        }
    }
    

    now it works !

    Output

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search