Skip to main content
JavaScript Bug Hunt Easy +10 XP

Off-by-One Error

This function should return the last element of an array, but it has a bug.

JavaScriptFind the bug
1function lastElement(arr) {
2 return arr[arr.length];
3}
The bug is on line 2

Select the correct fix

Show answer and explanation

Answer: arr[arr.length - 1]

Arrays are zero-indexed, so the last element is at index length - 1, not length.

Hint: Arrays start at index 0.

What this challenge tests

Bug Hunt in JavaScript: arrays, indexing.

Related challenges