Tip: Choose Save as PDF in the print dialog to download. Use A4 paper size.
This Reading beyond the end of an array 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 | |
|---|---|---|
| 1let scores = [5, 8, 9]; console.log(scores[3]); | AThe loop uses <= so the last pass reads scores[scores.length], which is undefined. It should use i < scores.length. | |
| 2console.log(scores[-1]); | Bscores[scores.length] | |
| 3The last valid index of an array is its length minus 1 | CThe array has 2 items, so the indexes are 0 and 1. colours[2] is undefined. Use colours[1] for the last item. | |
| 4Using length as the index reads past the end and gives undefined | Dscores[scores.length - 1] | |
| 5let colours = ['red', 'blue']; console.log(colours[2]); | EPrints undefined, because a 3-item array only has indexes 0, 1 and 2 | |
| 6for (let i = 0; i <= scores.length; i++) { console.log(scores[i]); } | FPrints undefined, because a negative index is not a valid position |
Complete each line of code by filling in the missing parts.
Shade in the letter of the line that contains an error.
arr[arr.length] — Reading an index past the last item (or a negative index) does not crash. It gives undefined. The last valid index is length - 1, so scores[10] in a 10-item array is undefined.let scores = [5, 8, 6];
console.log(scores[3]);let scores = [5, 8, 6];
console.log(scores[scores.length]);let scores = [5, 8, 6];
console.log(scores[-1]);let scores = [5, 8, 6];
console.log(scores[scores.length - 1]);let scores = [5, 8, 6];
let x = scores[5];
console.log(x === undefined);