Lessons · JavaScript · length and the last item
How many
"hello".length is 5 and [1, 2, 3].length is 3. length counts items; the last index is length - 1.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Is the field empty, does the list have anything, where does the last item sit: length answers all three, and off-by-one errors around it are the classic loop bug.
How to think about it
Use length for counts and emptiness (xs.length === 0). For the last item, at(-1) avoids the minus-one arithmetic.
Worked example
console.log("hello".length);5.console.log([1, 2, 3].length);3: arrays have it too.
console.log("".length, [].length);0 0.console.log("hello"["hello".length - 1]);o: the last character is at length minus one.console.log(["a", "b", "c"].at(-1));c: the same last item, with none of the minus-one arithmetic.
Your turn
The last character of a word.
const last = word[word.length - ];
Solve one with the tests running
The trap
length is not the last index. Reading arr[arr.length] gives undefined every time. And length can be assigned: arr.length = 0 empties the array, which is handy on purpose and alarming by accident.