Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
See how I programmed the solution to the random number challenge.
-
0:00
This challenge should have been pretty easy.
-
0:02
You already learned how to create a random number between two values in
-
0:05
stage three of this course.
-
0:07
However, now you're using a function that accepts arguments.
-
0:12
I didn't put anything but
-
0:13
the formula in the random.js file, so you had to remember how to create a function.
-
0:20
Because the function should produce a random value between two numbers,
-
0:24
we need to add two parameters to the function.
-
0:29
Then I'll just move the formula into our function and
-
0:33
place the parameters where they need to go.
-
0:36
The upper value goes here, and the lower value is here, and here.
-
0:45
I'll assign the result to a variable.
-
0:49
Then we'll return that variable and exit the function.
-
0:56
You can make this code even more compact.
-
0:58
You don't need to assign the formula to a variable and then return the variable.
-
1:03
Because the formula produces a value,
-
1:05
you can simply return the results of the formula like this.
-
1:10
Why can you do this?
-
1:12
Well, let's look at this formula.
-
1:13
It takes some information, the two variables and
-
1:16
runs it through a couple of JavaScript methods and does some math.
-
1:20
All of this code evaluates, as programmers say, to a single value, the random number.
-
1:26
All a return statement does is return a value.
-
1:29
It doesn't matter where that value comes from.
-
1:32
It can be stored in a variable, or it can just be the result of another function, or
-
1:36
some mathematical operations, as it is in this case.
-
1:40
Okay, now it's time to test this.
-
1:43
I'll just call the function a few times, and
-
1:47
print the results to the console each time.
-
1:51
[BLANK_AUDIO]
-
2:08
I'll save the file and preview the work space.
-
2:14
I'll open the console.
-
2:16
Looking good, some random numbers.
-
2:18
I'll reload.
-
2:19
More random numbers.
-
2:21
And you can see they're between the values that I specified in my code.
-
2:24
As you'll see in the next video, however, there is a problem with this function.
-
2:28
And you'll need to fix it.
You need to sign up for Treehouse in order to download course files.
Sign up