search

Home  >  Q&A  >  body text

Does javascript forEach create a new execution context for each array item, or does it just update the lexical environment of the current execution context?

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?

The

code 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
})

P粉663883862P粉663883862266 days ago455

reply all(1)I'll reply

  • P粉674876385

    P粉6748763852024-04-02 23:22:53

    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:

    for (const num of nums) {
        const foo = num
    }

    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 new foo 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 use var 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 because var is not block scope. This is my recommendation to never use var in new code One of the reasons.)

    reply
    0
  • Cancelreply