#59: arr.push(3)
Topic: arrays · Difficulty: ★
const arr = [1, 2];
console.log(arr.push(3));
console.log(arr);Output
3 [ 1, 2, 3 ]
Why
Array.prototype.push() mutates the array by appending the given argument(s) to the end, but its RETURN VALUE is not the pushed element and not the array itself — it's the array's new length after the push. Here [1, 2] had length 2, so after pushing 3 the length becomes 3, and that 3 is what gets logged first (which happens to equal the pushed value here purely by coincidence of the example numbers). Logging arr afterward shows the actual mutated contents, [1, 2, 3]. Confusing push's return value with the pushed element or the array itself is a common mistake, especially since unshift() behaves the same way, returning the new length too.