JavaScript JavaScript Basics Creating Reusable Code with Functions Variable Scope

Nelson J
Nelson J
5,984 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?

1 Answer

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.