vito yan
vito yan

Reputation: 135

What kind of scope does the variable belong to if we define a function variable outside of this function?

Consider this code

function foo(){
     foo.count = 1;
     console.log(foo.count);
}
foo.count = 2;
foo();
console.log(foo.count);

I expected the result would be 1, 2, but the actual result is 1, 1. This is confusing; I assigned a new value to foo.count = 2, but it seems not to work.

function foo(){
     console.log(foo.count);
}
foo.count = 2;
foo();
console.log(foo.count);

If I delete the assignment code in foo() function, the result is 2, 2.

So I want to know what scope the variable has if we define a function variable outside of this function? Does foo.count belong to the function scope or global scope?

Upvotes: 0

Views: 39

Answers (1)

Stephen Thomas
Stephen Thomas

Reputation: 14053

In your original code, when you execute foo() in line 6 you're setting the value to 1

Upvotes: 3

Related Questions