2018-10-10 22:03:03 +00:00
---
id: cf1111c1c11feddfaeb9bdef
2021-02-06 04:42:36 +00:00
title: Generate Random Fractions with JavaScript
2018-10-10 22:03:03 +00:00
challengeType: 1
2020-04-29 10:29:13 +00:00
videoUrl: 'https://scrimba.com/c/cyWJJs3'
forumTopicId: 18185
2021-01-13 02:31:00 +00:00
dashedName: generate-random-fractions-with-javascript
2018-10-10 22:03:03 +00:00
---
2020-12-16 07:37:30 +00:00
# --description--
2021-02-06 04:42:36 +00:00
Random numbers are useful for creating random behavior.
2018-10-10 22:03:03 +00:00
2021-02-06 04:42:36 +00:00
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`
2018-10-10 22:03:03 +00:00
2021-02-06 04:42:36 +00:00
**Note**
Like [Storing Values with the Equal Operator ](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator ), all function calls will be resolved before the `return` executes, so we can `return` the value of the `Math.random()` function.
2018-10-10 22:03:03 +00:00
2020-12-16 07:37:30 +00:00
# --instructions--
2018-10-10 22:03:03 +00:00
2021-02-06 04:42:36 +00:00
Change `randomFraction` to return a random number instead of returning `0` .
2018-10-10 22:03:03 +00:00
2020-12-16 07:37:30 +00:00
# --hints--
2018-10-10 22:03:03 +00:00
2021-02-06 04:42:36 +00:00
`randomFraction` should return a random number.
2018-10-10 22:03:03 +00:00
```js
2020-12-16 07:37:30 +00:00
assert(typeof randomFraction() === 'number');
2018-10-10 22:03:03 +00:00
```
2021-02-06 04:42:36 +00:00
The number returned by `randomFraction` should be a decimal.
2018-10-10 22:03:03 +00:00
```js
2020-12-16 07:37:30 +00:00
assert((randomFraction() + '').match(/\./g));
2018-10-10 22:03:03 +00:00
```
2021-02-06 04:42:36 +00:00
You should be using `Math.random` to generate the random decimal number.
2020-04-29 10:29:13 +00:00
2018-10-10 22:03:03 +00:00
```js
2020-12-16 07:37:30 +00:00
assert(code.match(/Math\.random/g).length >= 0);
2018-10-10 22:03:03 +00:00
```
2020-04-29 10:29:13 +00:00
2021-01-13 02:31:00 +00:00
# --seed--
## --after-user-code--
```js
(function(){return randomFraction();})();
```
## --seed-contents--
```js
function randomFraction() {
// Only change code below this line
return 0;
// Only change code above this line
}
```
2020-12-16 07:37:30 +00:00
# --solutions--
2021-01-13 02:31:00 +00:00
```js
function randomFraction() {
return Math.random();
}
```