What is the this keyword used for inside a function?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Medium
#JavaScript #Functions #JS Basics

Brief Answer

The this keyword is a reference to the object that called the current function. Simply put, it’s a way for a function to know “who owns it” or “on whose behalf” it works. 🎯


Full Answer

[this] is one of the most important concepts in JavaScript that often causes confusion. Let’s break it down very simply! 😊

What is this

[this] is like a function’s passport. It shows which object the function is bound to:

const user = {
  name: 'John',
  greet() {
    console.log('Hello, ' + this.name); // this → user
  }
};

Simple Examples

this in object methods

const cat = {
  name: 'Murka',
  meow() {
    console.log(this.name + ' meows'); // 'Murka meows'
  }
};
 
cat.meow(); // this → cat

this in regular functions

function showThis() {
  console.log(this); // depends on execution mode
}
 
showThis(); // undefined (in strict mode)

How this Works

When called as a method

const person = {
  name: 'Peter',
  sayName() {
    return this.name; // 'Peter'
  }
};
 
person.sayName(); // this → person

When called normally

const person = {
  name: 'Peter',
  sayName() {
    return this.name;
  }
};
 
const func = person.sayName;
func(); // this → undefined (in strict mode) ❌

When this is Useful

Working with object data

const counter = {
  value: 0,
  increment() {
    this.value++; // changing object property
  }
};

Universal methods

const dog = {
  name: 'Sharik',
  sound: 'woof'
};
 
const bird = {
  name: 'Chizhik',
  sound: 'chirp'
};
 
function makeSound() {
  console.log(this.name + ' says ' + this.sound);
}
 
// One function works for different objects!
makeSound.call(dog); // 'Sharik says woof'
makeSound.call(bird); // 'Chizhik says chirp'

Common Mistakes

Context loss

const obj = {
  name: 'John',
  greet() {
    console.log('Hello, ' + this.name);
  }
};
 
const greetFunc = obj.greet;
greetFunc(); // 'Hello, undefined' ❌

Arrow functions

const obj = {
  name: 'John',
  // Arrow function doesn't have its own this
  arrowFunc: () => {
    console.log(this.name); // undefined
  }
};

Simple Rules

  1. this — shows “who called the function” 🎯
  2. In methods — this → object that called the method 📦
  3. In regular functions — this → undefined (in strict mode) ⚠️
  4. Context loss — when passing methods as functions ❌
  5. Arrow functions — take this from outer scope 🏹

Understanding [this] helps write more predictable code and avoid errors. This is a very important topic for any JavaScript developer! 💪


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪