whatstheoutput_

#55: a.reverse() seen through another variable

Topic: arrays · Difficulty: ★

const a = [1, 2, 3];
const b = a;
a.reverse();
console.log(b);

Output

[ 3, 2, 1 ]

Why

const b = a does not copy the array — it copies the reference, so a and b both point at the exact same array object in memory. reverse() mutates that array in place (it doesn't create a new one), reordering its elements from [1, 2, 3] to [3, 2, 1]. Because b refers to the identical object as a, reading b afterward shows the reversed order too, even though reverse() was only ever called through the variable a. This is the same aliasing behavior that makes sort(), splice(), and push() all visible through every reference to the array.

More arrays puzzles

Play today's puzzle →