Generate random numbers

I am not getting the code, we have to generate random numbers from 0 to 1 in decimal numbers. Then why we declare result =0
while(result ===0) {
result = Math.random();

In my view we have to write the code like this
while(result !=0){
result = Math.random();

Any guidance please ?

Is this the exercise you are talking about?

I think the logic in the solution is that

  1. result is assigned the value 0.
  2. the condition of the while tests true because result === 0.
  3. result is assigned a new value by Math.random() which can be any number greater than or equal to 0 and less than 1.
  4. if Math.random() returns 0 then the while runs again but if Math.random() returns anything but 0 the while breaks and the return result is executed.

Your solution also works.

As long as you use Math.random and set a condition to return any number but 0 you will pass the tests. I won’t even try to think about how many possible solutions can be created that will work.

@DZamora54 Thank you for prompt response, Yes exactly I am talking about this exercise but this I am not getting some points.

1.why the result is assigned the value 0. ?
2.why the condition of the while tests true because result === 0. ?


In instructions it is saying that we have to generate numbers from 0 to 1. Then why we are assigning our while loop var result === 0 ?

You need to remember the difference between =, == and ===
result === 0 is checking if result equals 0 or not, it is not changning result

@ilenia Yes I got your point but, in instructions it is "Change randomFraction to return a random number instead of returning 0"

So my question is why we are checking 0, why we are not checking any number between 0 to 1 or 1 only ?

you shouldn’t return 0, but a random number.

random() returns a number that is 0 <= n < 1 (0 is included).

That is one way to avoid returning 0.

As in, you first set result to 0, then check if result is 0 and if it is you change the value (and if random returns a 0, that is done again)

There are many others.

BINGO now I understand. Thank you @ilenia. :slight_smile: