My title pretty much sums it all.
Can anyone enlighten me on...
"What is the 'Execution Context' in JavaScript?"
and on how it relates to 'this,' hoisting, prototype chaining, scope and garbage collection?
When you execute a script, the JavaScript engine creates a Global Execution Context and pushes it on top of the call stack. Whenever a function is called, the JavaScript engine creates a function execution context for the function, pushes it on top of the call stack, and starts executing the function.
Execution context (EC) is defined as the environment in which the JavaScript code is executed. By environment, I mean the value of this , variables, objects, and functions JavaScript code has access to at a particular time.
Up until now, we have seen how the JavaScript engine manages the execution context, Now let's understand how an execution context is created by the JavaScript engine. The execution context is created in two phases: 1) Creation Phase and 2) Execution Phase.
In JavaScript, “context” refers to an object. Within an object, the keyword “this” refers to that object (i.e. “self”), and provides an interface to the properties and methods that are members of that object. When a function is executed, the keyword “this” refers to the object that the function is executed in.
You're asking about several different concepts that aren't very closely related. I'll try to briefly address each.
Execution context is a concept in the language spec that—in layman's terms—roughly equates to the 'environment' a function executes in; that is, variable scope (and the scope chain, variables in closures from outer scopes), function arguments, and the value of the this
object.
The call stack is a collection of execution contexts.
See also this answer and this article.
Scope is literally that: the scope in which a variable can be accessed. Simplistically:
var x; function a() { var y; }
x
can be accessed from anywhere. When a
is invoked, x
will be in the outer scope. (Stored in the scope chain.)
In contrast, y
can only be accessed by code in a()
because it is limited to a
's scope. This is what the var
keyword does: restricts a variable to the local scope. If we omitted var
, y
would end up in the global scope, generally considered a bad thing.
Think of hoisting as more of a compile-time thing. In JavaScript, function declarations are "hoisted" to the top of their scope. In other words, they are parsed and evaluated before any other code. (This is opposed to function expressions, which are evaluated inline.) Consider the following:
a(); b(); function a() { } var b = function() { }
The call to a()
will succeed because its declaration was hoisted to the top; a
was assigned to automatically before program execution began. The call to b()
will fail with a TypeError
because b
will not be defined until line 4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With