6

Does JavaScript create a new execution context when executing a block to associate the its lexical environment with it.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
faressoft
  • 19,053
  • 44
  • 104
  • 146
  • Check section "13.2.14Runtime Semantics: BlockDeclarationInstantiation" in https://www.ecma-international.org/ecma-262/8.0/index.html#sec-blockdeclarationinstantiation – Mörre Oct 01 '17 at 18:12
  • Are you referencing a block outside of a function call or a block within a function call? – guest271314 Oct 01 '17 at 18:45

1 Answers1

9

No. An execution context is essentially a call stack frame, while the lexical environment is the current scope. No function gets called when a block is evaluated.

You can read in the specification for the evaluation semantics of blocks that it creates a new lexical environment (initialised with the variables in the block scope) that has the old environment as its parent, and "Set[s] the running execution context’s LexicalEnvironment to [that value]". After executing the statements in the block, the child environment is popped off again, but the running execution context did stay the same all the time.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • After the execution of the block is finished, LexicalEnvironment will be set again to the lexical environment of the function block right ? – faressoft Oct 01 '17 at 18:27
  • 2
    It will be set back to the lexical environment that was the execution context's lexical environment before entering the block statement. That's not necessarily the one of the `function`, it's whatever scope the block is found in. – Bergi Oct 01 '17 at 18:29
  • Really useful answer. Thank you – redchicken Apr 30 '20 at 10:39
  • even in the dev tools, you can see with block scope there is NO new callstack that gets created – Vipul Dessai Jul 11 '22 at 10:26
  • Awesome answer @Bergi + 1. I have a somewhat related question. Only code between braces of if, for, while, etc is considered block, i.e. a function (code between braces of a function) is NOT considered block, right? –  Jan 26 '23 at 19:58
  • 1
    @Daniel Yes, the braces around function bodies don't form a block. The function body still gets its own scope though. – Bergi Jan 26 '23 at 20:59
  • Great, thanks @Bergi, and when `any` function is called, a new execution context is started-created, right? –  Jan 26 '23 at 21:12
  • 1
    @Daniel Exactly – Bergi Jan 26 '23 at 21:17