JavaScript Global Execution Context

387 Views Asked by At

function callDad () {
  var numb = '0122822122';
  console.log('Calling ' + numb);
}

callDad();

1) Since the function callDad is declared globally it is saved in the global execution context before being invoked.
2) Once the function callDad is invoked a new execution context is created and executed on the stack.

Question: What happens to the original reference to the function in the global execution context? Is the function stored twice in memory?

Additional Q/A (For Reference):

Q: @Bergi Thanks for the reply. I think the question should be: Since the global execution context already stores the function in memory. Why does the new execution context have a new creation phase? Thanks

A: @Ash The creation phase is for the variables inside the called function body, specifically numb in your example

Q: @Rodrigo So once the function is called, it is referenced from the window object? Since reference in memory and a creation phase already exists for function declarations, then why do they say that every new execution context has a new creation phase?

A: Yes, the function is always referenced from window object. The execution context is just the scope and the scope chain (variables from other scopes in closures). Once the execution context is created, the creation phase allocates the memory for the variables inside that context. Oh, and remember that, in JS, you have function scope, not block scope.

2

There are 2 best solutions below

5
On

In the browser environment (but not in Node.js), the function will be attached to the window object, so it's created only once, and it stays there. So the reference to the function remains the same.

3
On

What happens to the original reference to the function in the global execution context?

Nothing. It gets stored usually only once.

(There might be some exceptions when a parsed & optimised function is stored multiple times for different argument types, but that's implementation specific and beyond this question)


Is the function stored twice in memory?

No. But a function's execution context is stored (and disposed of) multiple times - as often as you call the function.