@raina77ow recently helped me figure out computed property names. As part of their answer to my question, they shared a really tricky bit of code showcasing interesting aspects of JavaScript:
const increment = (() => { let x = 0; return () => ++x })();
const movingTarget = { toString: increment };
const weirdObjectLiteral = { [movingTarget]: 42 };
console.log( weirdObjectLiteral[movingTarget] ); // undefined
When I run that sample in the node CLI, that last line continually outputs undefined
, while the value x
in increment
continually increments.
If we replace const movingTarget = { toString: increment };
with const movingTarget = { [toString]: increment };
, this behaviour ceases to take place, and instead we get an output of 42
and the x
in increment
remains the same.
Can somebody help me understand why this is the case? What is it about JavaScript that makes things work this way?
Related Question: Does the x
in the function within increment
exist until we explicitly remove increment
from memory?