Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Declaring variables inside if statements.


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) {

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

if(player1.isTurn == true ) {

Thank you!

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