Why doesn't var foo = foo throw a ReferenceError?
Note: foo = foo does throw a ReferenceError.
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 ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With