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

Challenge at the end of the hoisting tutorial

Can anyone assist with the challenge at the end of the hoisting tutorial? I didn't realize I needed to be a programmer to understand the fundamentals of JavaScript. I'm completely frustrated.

I didn't realize you posted twice and already had an answer.

Your explanation was outstanding. Thank you again.

2 Answers

Hi Mark,

You start off with this code:

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

So it looks like the status variable is declared inside the if block and then assigned a string. Some languages have block level scope. This means that the status variable would only be available inside that if block because that's where it was declared. If you had some additional code inside that function after the if block it would not be able to use that status variable. It would be undefined after the if block.

Javascript does not have block level scope but it has function level scope. So what javascript does for you is it "hoists" the variable declaration to the top of the function.

So javascript sees the above code as if you had written:

function elevatorCloseButton(pushed) {
    var status;

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

Even though you've written your code like the first block, it is going to be run like the second block.

All the challenge is asking you to do is make that explicit rather than have javascript do it implicitly behind the scenes for you. Write it the second way because that's what's really happening.

Does that make sense?

That's awesome! Thank you very much Jason. I really appreciate the great explanation.

You're welcome