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 trialDaniel Spykstra
8,496 PointsDeclaring 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!
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
Alexander Einerskog
11,932 PointsHello 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.
Daniel Spykstra
8,496 PointsThank you Alexander! This makes way more sense now.
Himanshu Anand
4,666 Pointsconst 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