Let me, almost verbatim, repeat the start of the chapter on conditionals:
In ??? I pretended to have given
you the task of flipping a coin a number of times, and
then I proceeded with giving you:
the repo with cf0.js. In that code you
have
'use strict';
let tails = 0;
let heads = 0;
let flip;
flip = Math.random();
flip = Math.floor(flip * 2 + 1);
if (flip === 1)
tails++;
else
heads++;
flip = Math.random();
flip = Math.floor(flip * 2 + 1);
if (flip === 1)
tails++;
else
heads++;
flip = Math.random();
flip = Math.floor(flip * 2 + 1);
if (flip === 1)
tails++;
...
You will notice several things, lines 7 and 8 are repeated as 14 and 15, and again as 21 and 22, etc. They are obviously repeated because we need to execute them again. But what if we could wrap them together as sort of a package, so that every time we would execute both of them, we could do so with one statement? Less statements, same action. We like that. In fact there's a principle: DRY, Don't repeat yourself!
We also explained that Math.random is a JavaScript
built function that delivers a number to you.
Math.floor is another JavaScript built in function, that
takes the decimals away from the number you give it, and
returns the number without the decimals.
Let us create a custom made function that will do both getting a random number, and then twisting the result into a number that can interpreted as heads or tails as in flipping a coin.
'use strict';
function play() {
let x = Math.random();
x = Math.floor(x * 2 + 1);
return x;
}
We create a function named play. The name is
the programmers choice, but as with variables, good and
meaningful names are preferred. It creates a variable x,
assigns a random number to it, throws away the decimals
after multiplying with 2 and adding 1. The result, 1 or 2,
is returned. Returned to who? To the program using the
function. This would allow the usage
'use strict';
function play() {
let x = Math.random();
x = Math.floor(x * 2 + 1);
return x;
}
console.log(play()); // the returned x value from play is printed
// or
var slag = play(); // the returned x value from play is assigned to slag
console.log(slag);
Implementing this in our cf0.js we would get
cf0.js
'use strict';
function play() {
let x = Math.random();
x = Math.floor(x * 2 + 1);
return x;
}
let tails = 0;
let heads = 0;
let flip;
flip = play();
if (flip === 1)
tails++;
else
heads++;
flip = play();
if (flip === 1)
tails++;
else
heads++;
flip = play();
if (flip === 1)
tails++;
else
heads++;
flip = play();
if (flip === 1)
tails++;
else
heads++;
...The rationale behind functions is that things we need frequently can be coded as functions, and the use of these lines of code can be accomplished with one statement calling the function.