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 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';
    alert(person);
}

greeting();

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.

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