2018-09-30 23:01:58 +01:00
---
id: cf1111c1c11feddfaeb9bdef
title: Generate Random Fractions with JavaScript
challengeType: 1
2019-02-14 12:24:02 -05:00
videoUrl: 'https://scrimba.com/c/cyWJJs3'
2019-07-31 11:32:23 -07:00
forumTopicId: 18185
2021-01-13 03:31:00 +01:00
dashedName: generate-random-fractions-with-javascript
2018-09-30 23:01:58 +01:00
---
2020-11-27 19:02:05 +01:00
# --description--
2018-09-30 23:01:58 +01:00
Random numbers are useful for creating random behavior.
2020-11-27 19:02:05 +01: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-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01: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-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --instructions--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
Change `randomFraction` to return a random number instead of returning `0` .
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --hints--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
`randomFraction` should return a random number.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(typeof randomFraction() === 'number');
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
The number returned by `randomFraction` should be a decimal.
```js
assert((randomFraction() + '').match(/\./g));
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
You should be using `Math.random` to generate the random decimal number.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(code.match(/Math\.random/g).length >= 0);
```
# --seed--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
## --after-user-code--
2018-09-30 23:01:58 +01:00
```js
2018-10-20 21:02:47 +03:00
(function(){return randomFraction();})();
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
## --seed-contents--
```js
function randomFraction() {
// Only change code below this line
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
return 0;
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
// Only change code above this line
}
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --solutions--
2018-09-30 23:01:58 +01:00
```js
function randomFraction() {
return Math.random();
}
```