We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

This

The this keyword is perhaps one of the most rage-inducing parts of JavaScript. Once you understand it, it's not too bad, but it's far from intuitive (in my opinion).

Click to play video

Put simply, this refers to the context where a piece of code is executed... let's cover some of those cases:

Global Context

this refers to the window object in browsers or module.exports in Node.js (not global, as you might expect).

// in a browser
console.log(this);
// Window { ... }
// in Node.js
console.log(this);
// {}

Strict Mode

In strict mode (which we'll cover later, don't worry about it too much for now) this is undefined in the global scope in both the browser and Node.js.

"use strict";
console.log(typeof this);
// undefined

Method Context

Inside a standard method or a constructor, this refers to the object the method is called on.

const myObject = {
  message: "Hello, World!",
  myMethod() {
    console.log(this);
    console.log(this.message);
  },
};
myObject.myMethod();
// { message: 'Hello, World!', myMethod: [Function: myMethod] }
// Hello, World!

Arrow Functions

We'll cover arrow functions specifically in the next lesson - they're a bit of a special case.