4 ms·
The var statement declares a variable as local to the current scope and the entire current scope, not just from the var statement onward. These local variables
by sesqu 17y ago
The var statement declares a variable as local to the current scope and the entire current scope, not just from the var statement onward. These local variables shadow any existing variables from outer scopes.
Err, I tested this on Chrome's Inspector console, and I don't see such behaviour. The article says name should be undefined at the time of the comparison in the below code, but it isn't (and I frankly can't see why anyone would want it to be). Is this a feature of my execution environment, or have I just completely misunderstood what the author means?
(function(name){var cmp=name=="tim"; var name; return cmp})("tim") // returns true
- papercrane 17y agoSince the comparison happens before var is declared, it will always evaluate to 'true'. I believe the author was thinking about something like so: (function(name) { var cmp = function() { return name=="tim"; }; var name; return cmp();})("tim"); This still evaluates to true, but I believe it has to do with the rules of shadowing. If you change the declaration to 'var name="bob";' it will return false.
- creationix 17y agoGood catch, I'm looking into this one. I know I've seen this behavior before in some JS environment. I'm glad it's not the case for V8 and will shortly update the article.