We discussed conditionals earlier. With if
statements containing boolean expressions in parenthesis.
If you need to execute som code depending on various
values of the same variable such as
'use strict';
...
res = roll(6);
if (res === 1)
ones++;
else if (res === 2)
twos++;
else if (res === 3)
threes++;
else if (res === 4)
fours++;
else if (res === 5)
fives++;
else
sixes++;
...
A fragment of the solution for the section called “Assignment JS.Conds.0”.
With a programming construct, switch, this
could perhaps be done simpler:
'use strict';
...
res = roll(6);
switch (res) {
case 1:
ones++;
break;
case 2:
twos++;
break;
case 3:
threes++;
break;
case 4:
fours++;
break;
case 5:
fives++;
break;
case 6:
sixes++;
break;
}
...
or, equivalently
'use strict';
...
res = roll(6);
switch (res) {
case 1:
ones++;
break;
case 2:
twos++;
break;
case 3:
threes++;
break;
case 4:
fours++;
break;
case 5:
fives++;
break;
default:
sixes++;
}
...
You must notice two things from the last example:
There is a default clause that you may
use similarly to the else from the first
example. Until recently conventional wisdom dictated that
using default, it must
be placed last, just as its role model else,
this does not longer seem to be the case. Reports from
JavaScript and other languages seem to contradict that.
Henceforth we shak recommend placing it last because it
impoves readability.
Re Crockford at https://www.crockford.com/code.html: “A switch statement should be avoided, but when used should have this form:”
switch (expression) {
case expression:
statements
default:
statements
}
As is the case most of the time, I agree with Crockford most of the time, here though, I disagree on his deliberate lack of indentation.