Getting the last element
latestMessage() should return the newest message in the chat. Why is the preview always empty?
function latestMessage(messages) { if (messages.length === 0) return null; const last = messages[messages.length]; return last.text;}Show answer
line 3 · Off-by-one
Arrays are zero-indexed, so the last element is at length - 1. messages[messages.length] is undefined, and reading .text on it throws a TypeError.
const last = messages[messages.length - 1]; // or messages.at(-1)Interview follow-up: Bonus points for mentioning Array.prototype.at(-1).