JavaScript: Tally Winning Scores
featuring for loop, conditional ternary operator and template literal
for loop
for (let i=0; i<a1.length; i++) { ... }
The for loop iterates through two conditional ternary operator instructions described below. let
declares block-scoped variable i
local to the for
loop. i=0
sets the starting index. i<a1.length
limits the loop to three iterations, since arrays a1
and a2
contain three elements each. i++
indicates that each iteration will progress by one index step at a time, or a1[0]
, a1[1]
, a1[2]
for all three iterations.
conditional ternary operator
a1[i] > a2[i] ? c1++ : null
?
is the conditional ternary operator which is used to shorten the code, and which works with the :
operator. The comparisona1[i] > a2[i]
contains the >
comparison operator which takes the two operands a1[i]
and a2[i]
which are individual performance category scores values, based on the context of Rock Off!. c1++ : null
basically means that if the comparison returns true, then add 1 to the c1
counter, else return null
—which has the effect of skipping to the next instruction.
To paraphrase: if a1[i] > a2[i]
returns true, then add 1 to the c1
counter value, otherwise skip to the next instruction.
template literal
return `${c1}, ${c2}: Alice made "Kurt" proud!`
JavaScript’s template literals are string literals which can embed expressions. ${c1}
embeds the value stored in c1
. `...`
accent marks are used like quotation marks to specify template literal formatting. : Alice made "Kurt" proud!
is simply a hard-coded text string. solve([47, 67, 22], [26, 47, 12]
returns 3, 0: Alice made "Kurt" proud!
because the 1st rock band scored higher than the 2nd in all three categories.
running the script
console.log(solve([47, 7, 2], [47, 7, 2]),'0, 0: that looks like a "draw"! Rock on!')
console.log(solve([47, 67, 22], [26, 47, 12]),'3, 0: Alice made "Kurt" proud!')
console.log(solve([25, 50, 22], [34, 49, 50]),'1, 2: Bob made "Jeff" proud!')
Two arrays passed to the solve()
function can now be seen above. [47, 7, 2]
contains a set of three numbers. Each number represents total points scored in a specific category. '0, 0: that looks like a "draw"! Rock on!'
is the result expected to be seen in the CLI. 0, 0
indicates that both bands failed to win in a single category.