math.random() and comparison operator clarification

I know Math.random() generates random numbers, my question is:

1.What is going on by comparing it to .5 (or 50%)?

2.How does that trigger the if statement into working?

3.Is Math.random() getting its numbers from the variable1?

 variable1 = 8;
 while (variable1 > 0){
    If(Math.random() < .5){
    variable1--;
    }
 }

Answer

 variable1 = 8;
 while (variable1 > 0){
    If(Math.random() < .5){
    variable1--;
    }
 }
  1. What is going on by comparing it to .5 (or 50%)?

It’s like flipping a coin. Math.random returns a number between 0 and 1. It’s ‘heads’ if less than .5, ‘tails’ if it’s over. variable1 which starts at 8, gets subtracted by 1 every time (and only if) the coin flipped is ‘heads’

  1. How does that trigger the if statement into working?

Until variable1 subtracts down to less than 0, this loop will repeat and process the if condition

  1. Is Math.random() getting its numbers from variable1?

No, Math.random() is just generating a new number each time the if statement gets processed. variable1 is only changed when Math.random() is less than .5

Random, being what it is, could mean this while loop repeats infinitely. It’s unlikely, but there’s no law that says you ever have to eventually get tails on the flip.