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

How to assign status in if statement; best practices for hoisting

I cannot seem to get what they are trying to do. I know that they said to declare the variable at the top of the function i.e. var functionName = "Whatever", but it says that I need to declare the variable within the if statement. Can someone please tell me the correct code so I can compare it to my code?

2 Answers

Hello,

This is the right way to do it.

<script>

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

    }

    elevatorCloseButton(true);

    </script>

It's best practice to do so because of the default behavior of javascript.

When you declare a variable somewhere below the top of the code, Javascript automatically move that variable at the top of the scope and declare it there.

The interesting thing is that only declarations (var x;) but not initializations/assignments (var x = "something) are moved to the top.

That could cause wrong behavior of the code if you are not careful so to avoid that it's best practice to declare all the variables at the top of the scope and that way avoid any potential bugs.

You can see a good explanation ( besides Jim's:) ) here: http://www.w3schools.com/js/js_hoisting.asp

Good luck!

I see: I accidentally reversed two lines. This is what I had:

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

}

elevatorCloseButton(true);

// now I know exactly what was wrong and how to do the problem. Thanks for the clarification.