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
James McGuire
1,165 PointsHoisting JS elevator code
How does the var status; work? Is it like just saying open var. Or it has to be there even though it is not really needed. Like a pencil sharpener. If the cover is open it will not run but it is only there for looks.
2 Answers
Paul Hume
6,143 PointsHere is the best answer: Mozilla Quote off the site: "Using var outside a function is optional; assigning a value to an undeclared variable implicitly declares it as a global variable (it is now a property of the global object). The difference is that a declared variable is a non-configurable property of the global object while an undeclared is configurable."
Mike Rolih
9,766 PointsThe 'var' key is important for a few reasons: 1) it allows not only yourself but others to understand your code and the defined variables within it; 2) as Mozilla (via Paul) states, it allows you to understand Global vs. Local var declarations. If you declare a var outside a function, it is accessible anywhere because it is a global var; whereas if you defined a var within a function it is only accessible within that function (local). By not using the var keyword to define a var, you could accidentally modify a global var or create and define a new global var without realizing it, thus making the debugging process that much more complex.