The contextual side of JavaScript
Table of Contents
Introduction
The JavaScript execution context is basically the environment in which the JavaScript code is executed. It is important to understand the execution context because it affects the way your code will run. There are three main aspects to the execution context:
The global object:
This is the object that your code is running in. In a browser, the global object is the window object. Each function creates a new execution context. The global object is the object that is the parent of all other objects. That’s how we’re able to “chain” objects together (eg. window.document.body.textContent). Each function in our scripts also create a new execution context for that function. There is also eval(), but that’s won’t be covered here (it’s not commonplace). Each corresponds to:
The scope:
The scope is the current context of execution. It determines the “visibility” of the variables and functions. In the global scope function are visible and can be used anywhere. Function-level scope means that if a varaible is declared within a function it is only visible within that function. This could also conincide with: Block-level scope means that if a variable is declared within a block (eg. {}) it is only visible within that block.
The this keyword:
This keyword refers to the current object. In a browser, the this keyword refers to the window object. This is an exception case of sorts. This keyword can be binded globally or within an object or function. Common use case is to bind this to an object that is the parameter of a function (like the errors objects or events object).
Global scope
When your code is executed, it runs in the global scope. An example of global scope is:
If you create a variable in one function, it will be visible in all other functions.
This keyword
The this keyword refers to the current object. In a browser, the this keyword refers to the window object (As shown in the code previously). The this keyword is used to access properties and methods of the current object.
// object literal notation
// Will return my name
Ending thoughts / summary
Every function creates new execution context that has its own scope. Any variables or functions that are created in the function are only visible in that function. I will visit this later in a later article. They are not visible in the global scope. Scope is important because it determines the visibility of variables and functions. If a variable or function is not in the current scope, it will not be visible to your code. Hope this helps!