2

I'm looking into the working of the let block scope in JavaScript, in particular how the debug views of the browsers display the information

Using let within a for loop creates a block-scope, which the callback function timeoutHandler() has access to, all is good with this

In Chrome Dev Tools, the [[Scopes]] look as follows:

enter image description here

In Firefox Developer Tools, there is an extra Block Scope listed, which has timeoutHandler:timeoutHandler() as it's property. I only expected to see the Block Scope with j:1

enter image description here

What is this extra Block referring to?

Just wondering, as the lexical scopes I expected are shown in the Chrome debug, but not as expected in Firefox debug

Drenai
  • 11,315
  • 9
  • 48
  • 82
  • I am by no means an expert in js, but as I see it it's the block where `let j` is defined - that would be the `for {...}` block – birdspider Jan 02 '17 at 12:44
  • @birdspider yes, but there are 2 blocks in the Firefox view. It's the other block I'm asking about – Drenai Jan 02 '17 at 12:49
  • hm, the only thing that comes to mind is that the JS file/snippet gets it own overarching block (topmost/root block?) - which FF displays - but I didn't find any hard facts/standards for it - I checked [here](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-lexical-environments) but got lost fast – birdspider Jan 02 '17 at 13:50

1 Answers1

0

What is this extra Block with timeoutHandler referring to?

It seems to show the immutable binding that is wrapped around your named function expression. The function expression is actually interpreted as if your code was

'use strict';

for (var i = 1; i <= 2; i++) {
    let j = i;
    setTimeout( {
        const timeoutHandler = function() {
            console.log(j);
            debugger;
        };
        timeoutHandler
    }, 1000);
}

(OK, this block scope inside the call expression is obviously not syntactically valid, but I hope you get the meaning)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375