Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript Object Basics Filling Out the Play Method

Declaring variables inside if statements.

Hello!

So I finally figured out this code challenge. My question is are you able to declare a variable inside of an if statement? This code challenge wanted me to type my if statement as follows:

if (this.isTurn) {
  console.log();
} 

however this was not previously set as a variable. I kept typing out this:

if(player1.isTurn == true ) {
 console.log();
}  

Thank you!

object.js
const player1 = {
    name: 'Ashley',
    color: 'purple',
    isTurn: true,
    play: function(){
        // write code here.
      if (this.isTurn) {
        console.log(`${this['name']} is now playing!`);
      } else {
        console.log(`Not yet`);
      }

    }
}

3 Answers

Hello Daniel!

What they're doing is using the 'this' keyword to refer to the player1 object. Basically when you use 'this' inside of the player1 object, the computer interprets it as you writing 'player1', so 'this.isTurn' becomes functionally the same as 'player1.isTurn'.

The 'this' keyword can therefore be used to simplify code within objects by not needing to know that the object itself is called player1, but many find it confusing which is why some people opt to not use it.

Thank you Alexander! This makes way more sense now.

Himanshu Anand
Himanshu Anand
4,666 Points

const player1 = { name: 'Ashley', color: 'purple', isTurn: true, play: function(){ // write code here. if(this.isTurn===true) { console.log(${this['name']} is now playing!); } } }

//can you suggest what we are doing wrong