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

Nelson J
Nelson J
6,425 Points

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.

seth aruby
seth aruby
7,627 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