whatstheoutput_

#75: Mutating arguments[0]

Topic: scope · Difficulty: ★★★

function withoutDefault(a) {
  arguments[0] = 'changed';
  console.log(a);
}
withoutDefault('original');

function withDefault(a = 1) {
  arguments[0] = 'changed';
  console.log(a);
}
withDefault('original');

Output

changed
original

Why

In non-strict (sloppy) functions with simple parameters, the arguments object and the named parameters are LIVE-LINKED: writing to arguments[0] also writes to a, and vice versa, because they're really two views onto the same storage slot. withoutDefault has a simple parameter list, so that link is active and a becomes 'changed'. The moment a function's parameter list uses a default value (or rest or destructuring), the spec disables this aliasing entirely — arguments becomes an independent snapshot — so in withDefault, mutating arguments[0] has no effect on a, which stays 'original'.

More scope puzzles

Play today's puzzle →