Menu
Coddy logo textTech

Understanding the this Keyword

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 3 of 56.

The this keyword in JavaScript refers to the object that is currently executing the code. It allows you to access properties and methods of the current object.

Let's start with a basic object:

let person = {
  name: "John",
  age: 30,
  greet: function() {
    console.log("Hello, my name is " + this.name);
  }
};

In this example, when we call the greet method:

person.greet();

The output will be:

Hello, my name is John

Here, this.name inside the greet method refers to the name property of the person object.

challenge icon

Challenge

Add a method called getStatus to the player object that returns a string with the player's name and health using the this keyword.

Expected Output Format:
"Knight has 70 health"

Try it yourself

const player = {
    name: "Knight",
    health: 100,
    
    takeDamage: function(damage) {
        this.health -= damage;
    },
    
    // TODO: Add getStatus method here that returns a string with the player's name and health

};


// Test
player.takeDamage(30);
console.log(player.getStatus()); // Should output: "Knight has 70 health"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming