0
let mutateVariables = {};
let zoneNames = ['atr2', 'paint2'];
zoneNames.forEach(zone => 
  { mutateVariables[`zone${zone}`] = d => d[`${zone}fga`] / d[`${zone}fgm`] }
);

enter image description here

The output seems incorrect, at least in the chrome devtools console, as I was expecting the function to show as zoneatr2: d => d.atr2fga / d.atr2fgm. It looks like the zone was correctly appended into the function names, but not into the variables in the function. How can we tweak the code above such that the functions are created & displaying correctly in our object? Or perhaps everything is created just fine and this is just how the chrome devtools console is deciding to show the function?

Canovice
  • 9,012
  • 22
  • 93
  • 211
  • 2
    *everything is created just fine and this is just how the chrome devtools console is deciding to show the function* Yes – CertainPerformance Oct 23 '22 at 01:36
  • That's how Chrome logs the functions. The `zone` identifier within the function bodies is only _resolved_ once the function is executed, not at the time of creation – Nick Parsons Oct 23 '22 at 01:37
  • @NickParsons I just tested it and it not executed as expected – flyingfox Oct 23 '22 at 01:40
  • 1
    @lucumt I wonder how you tested it? Seems [to work](https://jsfiddle.net/cw8ugzb0/) ok for me – Nick Parsons Oct 23 '22 at 01:48
  • 1
    Closures are not created by variable substitution. – Bergi Oct 23 '22 at 02:02
  • 1
    @Bergi I’m curious about that comment. To what part are you referring to? I fail to identify what part should or should not have a closure. – OFRBG Oct 23 '22 at 02:12
  • 1
    The functions you're adding to the object are [closures](https://stackoverflow.com/q/111102/1048572), just as they should be - they close over the `zone` variable. But closing over something does change the code of the function, which is what is displayed. Like Nick said, the code works, just your expectations about the console are wrong. – Bergi Oct 23 '22 at 02:16

0 Answers0