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

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

Can't figure what to change in the code here, any help would be great.

3 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

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). Like this:

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.

Jacob Miller
Jacob Miller
12,466 Points

You need to create the variable "status" outside of the if statement, and then just assign a value to it inside the if statement.

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

Amazing, thank you both for your answers. I forgot about Hoisting.