Reputation: 65835
Why doesn't var foo = foo
throw a ReferenceError
?
Note: foo = foo
does throw a ReferenceError
.
Upvotes: 3
Views: 103
Reputation: 24801
When you use var keyword
var foo = foo
JavaScript hoisting creates foo and assigns it undefined value before code executes. So you can assign it any value which is foo here and foo itself is undefined so in fact you are again assigning undefined to foo through the same variable
When you are doing
foo = foo
you don't have left side foo defined earlier to assign a value to it.
When you are doing
var foo = bar
you don't have bar defined earlier.
Upvotes: 0
Reputation: 382394
When you declare
var foo = ...
you declare the variable for the entire scope (that is your function if not global), not just the code afterwards, contrary to other languages.
So in the right part of the assignment, foo
is already declared, even if it is still undefined
. There is no reference error.
Note that this property of var declaration in javascript can be a source of error. Because you might very well have (in more complex) this kind of code :
if (true) {
var a = 3; // do you think this is "local" ?
}
var a;
alert(a); // a is 3, did you expect it ?
Upvotes: 5
Reputation: 39980
Presumably, variable declarations are hoisted in Javascript. Which means the code
function bar() {
// some other code
var foo = foo;
}
is equivalent to:
function bar() {
var foo;
// some other code
foo = foo;
}
In fact, even the following works:
function bar() {
return foo;
var foo;
}
(And returns undefined
.)
Upvotes: 2
Reputation: 2625
JavaScript sorts var declaration to top, so at assignment time it is already declared (even if undefined):
var foo;
foo = foo;
Upvotes: 1