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

General Discussion

Help!

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

<script>

function elevatorCloseButton(pushed) {

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

}

elevatorCloseButton(true);

</script>

Can't figure this problem out. Please help!

2 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi Tyson Van Buren

The best practice for declaring variables within a function is to use the var keyword at the top of the function, not deep in the function (for example, not within an if/then statement).

function myFunction(friend) {
var saying;
   if (friend === true) {
      saying = "Hello";
   } 
}

It's recommended to put the variable declaration at the top of the function, because that's what JavaScript does anyway, via a process known as "hoisting" -- watch this video to http://teamtreehouse.com/library/javascript-foundations/variables/hoisting which discusses hoisting.

<script>

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

}

elevatorCloseButton(true);

</script>

its telling me that I should assign the 'status' in the if statement.

Dave McFarland
Dave McFarland
Treehouse Teacher

You should just declare the variable at the top of the function, not assign it anything:

var status; not var status = "I'll close when I'm ready.";