DEV Community

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

Posted on • Originally published at nicozerpa.com

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) {
        this.name = name;
    }
    sayName() {
        return `My name is ${this.name}`;
    }
}

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

capyDavid.sayName();
// ☝️ "this" is `capyDavid`,
//    returns "My name is David"

capyArianna.sayName();
// ☝️ "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;
sayDavidName();
// ☝️ It fails! There's nothing "left of the dot"
//   because there's no dot.

function quoteCapybara(sayNameFuntion) {
    return `A capybara says: "${sayNameFuntion()}"`;
}
quoteCapybara(capyArianna.sayName);
// ☝️ 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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay