Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

In the below code, is a new execution context created for each item in the array, or does the execution context stay the same and only it’s lexical environment’s environment record update?

The code does not throw an error, so I assume that a new scope (lexical environment) is created independent of the execution context but I’m not sure if I am right about that.

const nums = [1, 2, 3]

nums.forEach(num => {
  const foo = num
})

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There’s nothing special about the callbacks provided to standard library functions. They’re still functions, and they’re still called in the usual way functions are called.

In the below code is a new execution context created for each item in the array…

Yes. Whenever you call a function (in this case, when forEach calls its callback), a new execution context is created.

…The code does not throw an error, so I assume that a new scope (lexical environment) is created independent of the execution context…

Not (in this case) as a separate thing from creating a new execution context, no. As part of the standard process of calling a function.

In contrast, consider a for-of loop:

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

Here, there is no callback function to call; the body of the loop is just a block. But a new lexical environment object is created for each loop iteration, thanks to the way the semantics of block scope were defined. That means that, similar to the forEach callback, there is a new foo for every loop iteration, even though there’s no function call needed. (This is very handy if you’re creating event handlers or similar inside that block.) (If we’d used var instead, there wouldn’t be a new one each time, the var would jump out of the block to the surrounding function scope or global scope, since var is not block-scoped. This is one reason I suggest never using var in new code.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading