JavaScript · Module 3
Answers and explanations · Choose a path and repeat a task
Compare these references after your own attempt. You can read them at any time; they do not record a live model or vendor run.
JavaScript · Module 3
Compare these references after your own attempt. You can read them at any time; they do not record a live model or vendor run.
A: -1 is invalid data; 0 is Full; 1 is 1 places available in this early version. The branches distinguish invalid, full and available states. A broad truthiness test would not express all three rules.
B: moving the declaration into the loop also makes total unavailable to the final outside-loop console.log, so that log throws a ReferenceError. With a temporary log inside after the addition, you see 3, 0, 5 because each iteration initializes total again. Restore the declaration before the loop: now total survives between iterations and becomes 3, then 3, then 8. The final outside-loop log can read 8. The corrected sum follows example 03.
C:
const counts = [3, 0, 5, 0];
let availableEvents = 0;
for (const count of counts) {
if (count > 0) {
availableEvents = availableEvents + 1;
}
}
console.log(availableEvents);
This counts events, not places. Adding count itself would sum people instead. With an empty array the body never runs, so the initial zero is the correct result.