Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
Managing the number of copies
The driver can make three copies of the given page. Now you need to train it to make a different number of copies depending on the situation. You know the conditions, and that’s why you could write the program like this:
// Variable stores the necessary number of copies
var count = 3;
if (count === 2) {
muffin.print(page);
muffin.print(page);
}
if (count === 3) {
muffin.print(page);
muffin.print(page);
muffin.print(page);
}
In general, the approach is working, but no one writes programs like that. Imagine a program that can make one hundred copies of one page.
To make execution of these repeated commands convenient, there are loops in programming languages. For example, the loop for
:
for (var i = 0; i < count; i = i + 1) {
// repeated commands
}
If we write the loop for
like this, the actions inside curly brackets will be executed count
times.
We will postpone careful consideration of the contents of for
until the next task, but for now we’ll see how it works.
Modify the driver so that you can control the number of copies with the variable count
.
By the way, in the “Conditions” chapter, we looked into strict (===
) and approximate (==
) equality. Why is it that strict equality is used in the example above?
Because such a comparison helps to avoid errors. For example, this comparison will work if we use approximate equality:
if ('003' == 3) {
// …
}
The same check using ===
will not work, because line '003'
is not the same as number 3
. In our program, the number of copies is written with a number and in all comparisons, we expect a number. Therefore, we use strict equality to make sure that inappropriate values do not slip into our program.
Using strict equality is good practice. Use it and nothing else in all cases where possible.
- script.js
Thanks! We’ll fix everything at once!
The code has changed, click “Run” or turn autorun on.
Result
Replace command duplication with the for
loop.
- Delete the
muffin.print
commands and replace them with the loop:for (var i = 0; i < count; i = i + 1) { }
. - Inside the loop, add the command
muffin.print(page)
. - Change the value of the variable
count
to5
and make sure that the number of printed copies has changed.
Comments