Sitemap
Better Programming

Advice for programmers.

Understanding the “this” Keyword in JavaScript

How the value of “this” is assigned in different scenarios

4 min readJan 30, 2018

--

Image
Image credit

In this article, we’re going to learn about the JavaScript keyword this and how the value of this is assigned in different scenarios. The best way to digest the content of this article is by quickly executing the code snippet in your browser’s console. Follow the below steps to launch the console in your Chrome browser:

  • Open new tab in Chrome
  • Right click on page, and select “inspect element” from the context menu
  • Go to the console panel
  • Start executing the JavaScript code

Objects are the basic building blocks in JavaScript. There’s one special object available in JavaScript, the this object. You can see the value of this at every line of JavaScript execution. The value of this is decided based on how the code is being executed.

Before getting started with this, we need to understand a little about the JavaScript runtime environment and how a JavaScript code is executed.

Execution Context

The environment (or scope) in which the line is being executed is known as the execution context. The JavaScript runtime maintains a stack of these execution contexts, and the execution context present at the top of this stack is the one currently being executed. The object this refers to changes every time the execution context is changed.

“this” Refers to a Global Object

By default, the execution context for an execution is global — which means if a code is being executed as part of a simple function call, then this refers to a global object.

The window object is the global object in the case of the browser. And in a NodeJS environment, a special object called global will be the value of this.

For example:

Immediately Invoked Function

--

--

Responses (18)