Random numbers are useful for creating random behavior.
JavaScript has a Math.random() function that generates a random decimal number between 0 (inclusive) and not quite up to 1 (exclusive). Thus Math.random() can return a 0 but never quite return a 1
Note
Like Storing Values with the Equal Operator, all function calls will be resolved before the return executes, so we can return the value of the Math.random() function.
Instructions
Change randomFraction to return a random number instead of returning 0.
There’s a problem with the code included in that guide post. The for loop doesn’t contain any code and is therefore pointless.
All you need to satisfy this challenge is:
function randomFraction() {
// Only change code below this line.
return Math.random();
// Only change code above this line.
}
Technically there is a small chance that this could return 0, which would fail a test. So you could do something like:
function randomFraction() {
// Only change code below this line.
var result = 0;
while (result === 0) {
result = Math.random();
}
return result;
// Only change code above this line.
}
The following is an exercise that basically uses the return. In fact, it is the above exercise (using bum instead of num.)
function timesFive (bum) {return bum * 5;}
timesFive(3);
so it looks like you can use paramaters after a return. The challenge said I passed it but I think it may have been a false positive for the math.random() function that was actually named randomFraction()
in your solution, which will return a random decimal number (the point of the challenge). The Math.random function does not have any parameters, so the i you passed in just gets ignored and so it has the same effect as:
function randomFraction() {
// Only change code below this line.
var temp = Math.random();
if (temp === 0)
{
randomFraction();
}
return temp;
// Only change code above this line.
}