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 JavaScript Foundations Variables Hoisting

Rodney Brooks
Rodney Brooks
1,116 Points

HELP!! I cant get to step 1 w/ a Solution to the Task

The Task: Alter the 'elevatorCloseButton' function to follow the best practices in declaring variables within the scope of the function.

Code: <script> function elevatorCloseButton(pushed) {

    if (pushed) {
        var status = "I'll close when I'm ready.";
    }

}
elevatorCloseButton(true);
</script>

I feeling very low because after watching the videos & taking each quiz leading up to this task, I had no errors or incorrect answers. But I can't seem to get to first base on this last Challenge Task - I'm sure someone out there can give me a nudge towards the taking the first step in solving this problem...

-Rod

3 Answers

Janek Rezner
Janek Rezner
12,973 Points

this should work?

function elevatorCloseButton(pushed) {
var status;

if (pushed) {
status = "I'll close when I'm ready.";
}

}

elevatorCloseButton(true);

Hi Rodney,

Right now the status variable is declared inside the if block. Some languages have block level scope. Meaning that the status variable would only be available inside that if block. Any other code inside that function would not have access to the status variable.

However, javascript does not have block level scope but has function level scope instead. So even though the variable is declared inside the if block, javascript treats it as if you declared it at the beginning of the function. It "hoists" the variable declaration to the top of the function.

So rather than have javascript do this for you behind the scenes the challenge simply wants you to make that explicit and declare the variable at the top yourself since that's what's really happeining. You still want to do the string assignment inside the if block but the variable should be declared at the top.

Rodney Brooks
Rodney Brooks
1,116 Points

Thanks guys - Jason your explanation really helped me and I appreciate your correct answer Yann. I guess I was approaching this question incorrectly and made it more complicated than it was originally intended. Thanks again!