Tip: Choose Save as PDF in the print dialog to download. Use A4 paper size.
This Common bugs in functions and arrays worksheet is part of the ACARA Digital Technologies Years 9–10 — Modular and Object-Oriented Programming (JavaScript) journey. Print it as a booklet?
Shade in the A or B circle for each question.
Draw a line connecting each item on the left to its match on the right.
| Left column | Right column | |
|---|---|---|
| 1for (let i = 0; i <= arr.length; i++) | AThe total is set to 0 inside the loop, so it resets every pass and ends up holding only the last number. | |
| 2function add(a, b) { a + b; } | BMissing return: the sum is worked out but never sent back, so add(2, 3) gives undefined. | |
| 3A total must be set to 0 once, before the loop, so it keeps adding up across every pass. | CLoop limit bug: <= runs one step too far, so the last pass reads arr[arr.length], which is undefined. | |
| 4To run a function and get its result you must call it with brackets, even if it has no parameters. | Dconst score = getScore(); | |
| 5for (const n of nums) { let total = 0; total += n; } | EThe function is not called because the () are missing, so it prints the function itself, not its result. | |
| 6console.log(getScore); | Flet total = 0; for (const n of nums) { total += n; } |
Complete each line of code by filling in the missing parts.
Shade in the letter of the line that contains an error.
bug — A mistake in code that gives wrong results. Common ones: a missing return, <= instead of < in an index loop, a total set inside the loop, or calling a function without ().for (let i = 0; i < scores.length; i++) {
console.log(scores[i]);
}function double(n) {
return n * 2;
}let total = 0;
for (const n of nums) { total += n; }
console.log(total);function greet() { return "Hi"; }
console.log(greet());for (let i = 0; i <= nums.length - 1; i++) {
console.log(nums[i]);
}