Member-only story

Understanding JavaScript’s ‘this’ Keyword

Your Guide to Making Sense of JavaScript’s Infamously Confusing Keyword

Max N
2 min readFeb 25, 2024
Photo by Brad on Unsplash

Mastering the ‘this’ keyword in JavaScript is considered somewhat of a rite of passage for developers. The flexible ways it binds to values often trip up both beginners and experienced programmers alike.

Luckily, while complex, ‘this’ follows a set of predictable binding rules. Understanding these gives us the power to intentionally control context and write cleaner component logic.

Let’s demystify how ‘this’ works step-by-step!

Dynamic Binding

The key thing that makes ‘this’ confusing is its binding is dynamic instead of lexical. Its value depends on how the containing function is called, not where the function is defined.

Consider this example:

function logThis() {
console.log(this);
}

logThis(); // logs the global object (window/global)

Even though logThis is defined on its own here, when we call it by itself, the this value points to a default global object instead. The binding happens dynamically on invocation.

Binding Rules

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet