Javascript’s magic “this”

Rahadian Permana
2 min readFeb 18, 2024

In the realm of JavaScript, the keyword “this” holds a certain magical — and occasionally perplexing — power. Understanding “this” is a rite of passage for any JavaScript developer, as it plays a crucial role in how your code interacts with objects and functions. In this quick read, we’ll crack open the secrets of “this” and illuminate its behavior with simple examples.

What exactly is “this”?

“this” is like a chameleon — its value changes depending on the context in which it’s used. Think of it as a reference to the object that ‘owns’ the currently running code.

“this” in different disguises

  1. Global “this”: Alone in the open (not inside any function), “this” points to the global object (window in browsers).
console.log(this); // Outputs the 'window' object

2. Regular Functions: Inside a regular function, the value of “this” gets a bit unpredictable, usually defaulting to the global object.

function whoAmI() {
console.log(this); // Might also output the global object
}
whoAmI();

3. Object Methods: The most common use-case! Inside a method attached to an object, “this” takes on the form of that object.

const cat = {
name: "Whiskers",
meow: function() {
console.log(`${this.name} says meow!`);
}
}
cat.meow(); // Outputs "Whiskers says meow!"

4. Constructors: Using the “new” keyword? “this” represents the freshly created object.

function Dog(breed) {
this.breed = breed;
}
const fido = new Dog("Labrador");
console.log(fido.breed); // Outputs "Labrador"

5. Arrow Functions (ES6 magic): Arrow functions don’t get their own “this”. They inherit “this” from the scope where they’re defined, making them super handy in scenarios like callbacks.

const person = {
name: "Alice",
tasks: ["Code", "Debug", "Coffee"],
showTasks() {
// Regular function 'this' confusion
this.tasks.forEach(function(task) {
console.log(`${this.name} needs to ${task}`); // Might not output what you expect
});

// Arrow function to the rescue!
this.tasks.forEach((task) => {
console.log(`${this.name} needs to ${task}`); // Works as intended
});
}
};

person.showTasks();

Tips & Tricks

  • Avoid Confusion: Arrow functions were born to provide clarity. They “capture” the this value from their surrounding scope.
  • Explicit Setting: Use .call(), .apply(), or .bind() to assign "this" a specific value when calling a function.

The Journey Continues

This is just a glimpse into the dynamic nature of “this”. While it may seem puzzling at first, understanding its transformations will bring a fresh perspective to your JavaScript code, helping you write more elegant and maintainable solutions.

Let me know if you’d like more advanced examples or have specific “this” challenges you want to conquer!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Rahadian Permana
Rahadian Permana

Written by Rahadian Permana

Software Engineer And History Enthusiast

No responses yet

Write a response