0

I have come across an anomaly between Firefox and Node.js. Given the following code:

'use strict';
const obj = {};
for (let f of ['left', 'right']) {
  obj[f] = function() {
    return f;
  };
}
console.log(obj.left());
console.log(obj.right());

Firefox (48.0) outputs

right
right

while Node.js (6.4.0) outputs

left
right

Both on Ubuntu 14.04. I didn't have the possibility to test with other ECMAScript engines.

Any idea what is the reason for the difference, and which implementation is correct with respect to the specification?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Have you tried enabling strict mode? – Bergi Sep 15 '16 at 16:42
  • @Bergi same output, I have edited the original question though to reflect that. –  Sep 15 '16 at 16:46
  • I'm not in the situation to check, but I would believe node behavior is the correct one here – John Dvorak Sep 15 '16 at 16:48
  • Ah, so it's not ['let' Keyword in Firefox 43.0.2 not working](http://stackoverflow.com/q/34684892/1048572) – Bergi Sep 15 '16 at 16:49
  • @Bergi nope, I would have put 'const' if Firefox didn't currently break on such constructions. But that is besides the point. Even if I use a traditional loop, I get the same results. –  Sep 15 '16 at 16:51

1 Answers1

1

Your version of Node is correct here, let in a for loop should have block scope.

FF 48 simply doesn't support "for/for-in loop iteration scope" yet, it appears to be fixed with FF 51.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Additional verification that node/v8 is correct here is the relevant tc39/test262 test [here](https://github.com/tc39/test262/blob/44c65fd02ae71873499f1a4151ff01b7e23eb677/test/language/statements/for-of/let-fresh-binding-per-iteration-for-of.js). – mscdex Sep 15 '16 at 16:57
  • @mscdex: I didn't think that "additional verification" such as a spec link was necessary, `let` scoping in ES6 is common knowledge by now :-) – Bergi Sep 15 '16 at 16:59
  • I'm just pointing out that that repo is handy if in doubt about JavaScript behavior (in general), since it's maintained by the people who write the language specifications. Can't get more definitive than that. – mscdex Sep 15 '16 at 17:01
  • @mscdex I would consider [the spec itself](http://www.ecma-international.org/ecma-262/6.0/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset) to be more definitive than any spec tests :-) – Bergi Sep 15 '16 at 17:03
  • IMHO the tests are *easier* to read/understand for most people than the language in the spec. – mscdex Sep 15 '16 at 17:12