Understanding Context in JS

Know what you’re working with and how to define it

Lauren Cunningham
The Startup
4 min readNov 7, 2020

--

image from Stackify

What is Context and Why do I care?

One of the largely misunderstood fundamental concepts of JavaScript is the ‘this’ keyword. While we can write JS code without this knowledge, getting some clarity here can lead to a greater understanding of the language itself and may even reduce mysterious bugs!

First, we need to know a little about Execution Context. To put it simply, Execution Context is the management of what is currently running. Obviously, things would get really ugly if all of our code was called at the same time. There must be an order and that order is handled via the Execution Context. The rules for what gets run first abide by the order of lexical scoping.

Lexical Environments / Scope

There’s much to understand when it comes to scope. For the purpose of this article, we will cover the basic ideas.

When our program starts, a JavaScript object is automatically created with a top-level lexical environment called Global Scope. Functions and variables that are nested within functions or have been encapsulated in curly brackets will have their own scope.

In the diagram below, all the different highlighted colors represent a different scope level. One thing to note here is that global variables are accessible everywhere. However, variables and functions that are not defined at the global level are only accessible within their scope.

diagram by JavaScript Teacher

Where are we?

JavaScript is not just a functional language, but also an Object-Oriented language and as such, it has the ability to contain ‘objects’ with characteristics and relationships that we can assign to reflect ‘real-world’ interactions. (You can read more about Object-Orientation in my previous blog post, How Rubyists Use Abstraction.)

When working with OO, it’s crucial to keep a mental note of which object is invoking each function. The reserved word ‘this’ refers to the object that is calling the currently running function. So, how do we know what ‘this’ is referring to? By remembering the scope that we are in! The global object in a browser is ‘window’. The global object in NodeJS is simply called ‘global’.

For example, try typing this in the console of your browser…

Now try this one…

When calling a function using dot notation like in the last example above, ‘this’ is referring to whatever is on the left side of the dot.

Explicit Binding

Now that we have discussed the default pattern of ‘this’, I’d like to point out that we do have the power to explicitly define the object that we want to call a specific function. There are a few pre-defined methods that change the behavior of ‘this’, you can remember these methods with the acronym CAB.

Call
Apply
Bind

Call

Let’s say you want to invoke a function and pass it a specific object to assign to ‘this’. You can do so by using the call method.

Take a look at this code…

If we want the object stacey to call the sayName function, we can pass stacey as the argument to the call method like so…

This would return ‘My name is Stacey’.

Apply

The apply method works in a similar fashion to ‘call’, but we can pass in collection or array of arguments.

Consider the code below. Using apply, the function will take in an array as an argument and return ‘I know JavaScript, Ruby and Python’.

Bind

The difference between call or apply and bind is that bind will return a new function that we can call later, instead of invoking the original function. When we call it later, it will still be ‘bound’ to the object we passed as an argument.

In the example below, by binding object to myFunc, ‘this’ will be equal to the argument that we passed in.

photo credit to Iqbal M Ipel

Bind is also frequently used for event listeners, since the default ‘this’ of an event listener is the window itself.

Wrapping it Up

The big take-away here is that ‘this’ is used to identify the object that is invoking the function that is currently being run. We have the power to explicitly set the ‘this’ keyword by using call, apply or bind. I encourage you to get comfortable with these keywords. Knowing what ‘this’ is referring to at any given line of code, will help you avoid confusing errors in the future and knowing how to manipulate ‘this’ will give you more control over the output you are recieving.

Resources

Lexical Environment Tutotial
‘this’ Keyword in JavaScript
Call, Apply and Bind Video

--

--