In the code below, is a new execution context created for each item in the array, or does the execution context remain the same and just the environment record of the lexical environment is updated?
Thecode does not throw an error, so I assume the new scope (lexical environment) is created independently of the execution context, but I'm not sure if I'm correct.
const nums = [1, 2, 3] nums.forEach(num => { const foo = num })
There is nothing special about the callbacks provided to standard library functions. They are still functions and are still called in the usual way of calling functions.
Yes. Whenever you call a function (in this case, when
forEach
calls its callback), a new execution context is created.(in this case) is not separate from creating a new execution context, no. As part of the standard procedure for calling functions.
In contrast, consider a
for-of
loop:There is no callback function to call here; the loop body is just a block. However, because of the way block scope semantics are defined, a new lexical environment object is created for each loop iteration. This means that, similar to the
forEach
callback, there is a newfoo
for each loop iteration, even if no function call is required. (This is very convenient if you want to create event handlers or similar event handlers inside the block.) (If we usevar
instead, we won't have a new one every time,var
will jump out of the block into the surrounding function scope or global scope becausevar
is not block scope. This is my recommendation to never usevar
in new code One of the reasons.)