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 trialReagan Schiller
10,072 Pointshelp with challenge
can't figure out how to code this challenge. when I define the status in the if block i am told to put it at the top, when i put it at the top I am told to put it in the if block, when i put it in both it tells me I should only enter it once.
2 Answers
Dave McFarland
Treehouse TeacherCheck out this discussion on the same code challenge: https://teamtreehouse.com/forum/hoisting-objective
In general, you want to declare a variable with the var
keyword at the top of a function, even if you don't set the value of the variable until later in the function:
function myFunction(y) {
var x;
if ( y === true ) {
x = true;
} else {
x = false;
}
return x;
}
Adam Moore
21,956 PointsYou might need to declare your variable at the top inside the if statement, so that the first line of code inside of the if function (after the first curly bracket) is the variable declaration. So instead of using a 'y' variable like:
var x=2;
if(x=2){
x=x+1;
y=2;
return x+y;
}
You may need to declare it like this (which I'm pretty sure is what Javascript does when it compiles the code):
var x=2;
if(x=2){
var y;
x=x+1;
y=2;
return x+y;
}