Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't {var foo = foo} throw a ReferenceError?

Why doesn't var foo = foo throw a ReferenceError?

Note: foo = foo does throw a ReferenceError.

like image 497
Mohsen Avatar asked Mar 06 '26 20:03

Mohsen


1 Answers

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 ?
like image 189
Denys Séguret Avatar answered Mar 08 '26 09:03

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!