whatstheoutput_

#97: delete on an existing vs missing key

Topic: objects · Difficulty: ★

const obj = { a: 1 };
console.log(delete obj.a);
console.log(delete obj.b);
console.log(obj);

Output

true
true
{}

Why

The delete operator's return value answers 'is this property now absent?', not 'did I actually remove something that was there'. delete obj.a removes an existing, configurable property and returns true. delete obj.b targets a key that never existed in the first place — but since obj.b is still absent afterward, that also counts as success, so it returns true too. delete only returns false when a configurable-false property refuses to be removed. Either way, obj ends up empty.

More objects puzzles

Play today's puzzle →