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 trial2 Answers
Dino Paškvan
Courses Plus Student 44,108 PointsIn JavaScript, variable declarations get hoisted to the top of the scope they were declared in. This may sound complicated, but here's what happens.
You declare a variable and assign value to it like this:
var myVariable = "Some text";
Even though you think of this as a single statement, the JavaScript engine won't see it that way. It actually sees two statements here. The first one is the variable declaration: var myVariable;
. The second one is the value assignment: myVariable = "Some text";
.
When your code is being run on a webpage, several things happen. The code gets parsed, compiled and optimized before the browser runs it. Different parts do different things. In this case, the compiler takes care of the variable declaration (the first part) during compilation. And the engine handles the assignment (the second part) during the execution.
Because of this, the compiler hoists the variable declaration to the top of the scope. This basically means that it moves the declaration to the top of the function in this case.
So if you have something like this:
function () {
// some code
var myVar = "Something";
// some other code
}
it will get converted into this:
function () {
var myVar;
// some code
myVar = "Something";
// some other code
}
This is why it's recommended to do this manually while writing a program to avoid confusion.
Your job is to break down the status variable declaration and assignment into two pieces. Leave the assignment where it is, inside the if
statement, and move the declaration to the top of the function.
Luiza Pantoja
13,269 PointsThank you Dino, your answer was very helpful!
Dean Hollstrom
9,445 PointsDean Hollstrom
9,445 PointsI just got stuck here myself, thanks for posting this explanation, really helpful!