whatstheoutput_

#46: arr.length = 1 then arr.length = 4

Topic: arrays · Difficulty: ★★

const arr = [1, 2, 3];
arr.length = 1;
console.log(arr);
arr.length = 4;
console.log(arr);

Output

[ 1 ]
[ 1, <3 empty items> ]

Why

The length property of an array is writable and directly controls the array's contents, not just a read-only count. Setting arr.length = 1 truncates the array immediately, permanently discarding every element from index 1 onward, leaving just [1]. Setting length to a larger value afterward, arr.length = 4, grows the array back out, but the newly added slots are not filled with undefined values — they are genuine empty holes, the same kind delete or a sparse array literal produces, printed as '<3 empty items>'. Both directions of assigning .length are legal and commonly used, but only one of them creates real elements.

More arrays puzzles

Play today's puzzle →