Harry Blue
Harry Blue

Reputation: 4502

Execution context's in JavaScript

I am trying to grasp execution contexts and have a question around for loops.

Consider the following...

function copyArrayAndMutate(array, instructions) {
  let output = []
  for(let i = 0; i < array.length; i++) {
    output.push(instructions(array[i]));
  }
  return output;
}

function multiplyByTwo(input) {
  return input * 2;
}

const result = copyArrayAndMutate([1,2,3], multiplyByTwo)

At a high level, I understand that these functions will be defined in the Global Execution Context, once invoked, they will create their own local execution context and the thread of execution will move into that context, with entries for the context being pushed to the stack.

My question is, will the for loop have it's own execution context? If so, and an execution context has it's own memory, how does output still exist within that for loop's context?

Is this because the local execution context of the for loop, exists within context of copyArrayAndMutate?

Upvotes: 2

Views: 1801

Answers (2)

Rafa Romero
Rafa Romero

Reputation: 2716

My question is, will the for loop have it's own execution context?

NO. The foor loop won't have it's own execution context. Only functions creates a new execution context.

Each time a function is called, a new execution context is created, even if the function call is inside another function definition. The scope that the function has available is defined by its lexical environment:

enter image description here

Anyway, the execution context of the for loop is the one created by copyArrayAndMutate function, that is the scope used by the for loop is the one that belongs to the copyArrayAndMutate execution context, that's why the loop has access to the output variable.

Upvotes: 2

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10127

My question is, will the for loop have it's own execution context?

Nope.

Context and variable scope in ES6 loops and forEach

Upvotes: 1

Related Questions