Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Basics (Retired) Creating Reusable Code with Functions Variable Scope

person variable without the 'var' keyword in the console.

Following on the examples shown in the video, I decided to try it out in the JS console.

function greeting() {
    person = 'Alex';


That alerts 'Alex' from the get go without adding the keyword var

I then define a variable person with the value of george. Like so,

var person = 'George'

And finally call greeting() again but the browser still alerts me with the value 'Alex' when it should return the value 'George'. Given what the video says, it doesn't seem to work. Any reason why?

2 Answers

Carl Evison
Carl Evison
2,656 Points

When JavaScript compiles your code all variable declarations using var are hoisted to the top of their functional/local scope (if declared inside a function) or to the top of their global scope (if declared outside of a function) regardless of where the actual declaration has been made.

So it makes sense knowing this that you are still alerting Alex because you're overriding the person variable which has now been hoisted above your function.

seth aruby
seth aruby
9,291 Points

Nelson, If you had pretty much done anything else with the person variable but call the the greeting() function you would've seen that once you declared that person='George' then, in fact, person would have been 'George'. For instance, if you had written person to the console using console.log(person) then the result would have been 'George'. Or document.write(person). But as soon as you called greeting() you reset the value of the variable person to be equal to 'Alex' and that is why you were alerted as such... hope that helps