DEV Community

Nico Zerpa (he/him)
Nico Zerpa (he/him)

Posted on • Originally published at

Small trick to understand the `this` keyword

The this keyword is one of the biggest headaches for anyone learning JavaScript. In this article, I won't go too deep into how the keyword works, but I will give you a quick tip to make it easier to handle.

As a general rule, the this keyword represents what's left of the dot when you're calling the method. Let's see an example:

class Capybara {
    constructor(name) { = name;
    sayName() {
        return `My name is ${}`;

const capyDavid = new Capybara("David");
const capyArianna = new Capybara("Arianna");

// ☝️ "this" is `capyDavid`,
//    returns "My name is David"

// ☝️ "this" is `capyArianna`,
//   returns "My name is Arianna"

Enter fullscreen mode Exit fullscreen mode

In JavaScript, functions are values. That is, you can pass functions as arguments, or assign them to variables. But when you do it, things get tricky:

const sayDavidName = capyDavid.sayName;
// ☝️ It fails! There's nothing "left of the dot"
//   because there's no dot.

function quoteCapybara(sayNameFuntion) {
    return `A capybara says: "${sayNameFuntion()}"`;
// ☝️ It fails too
Enter fullscreen mode Exit fullscreen mode

In the last example (the quoteCapybara function), why does it fail when you correctly passed the function as capyArianna.sayName? Because the function is executed inside the quoteCapybara function. There, it's run as sayNameFunction, so there's nothing "left of the dot".

In those cases, the most recommended solution is to change quoteCapybara so that it receives the capybara object as the parameter.

Become a Better JavaScript Developer
Easy, actionable steps to level up your JavaScript skills, right to your inbox. Click here to subscribe

Top comments (0)