|
|
|
|
|
by ajanuary
4181 days ago
|
|
> ... before, if I wanted to know if `x` is defined, i could write `typeof x !== "undefined"`. In all cases. And the result of that statement would never be a throw. Now, if I want to know if x is defined, there are at least two kinds of "undefined", one that will be returned by `typeof x` as "undefined", and another where I am not allowed to mention `x` at all, including to do `typeof x`. You can still write 'typeof x !=== "undefined"' and not worry about an exception being thrown. There are pretty much no situations where you're going to write legitimate code and 'typeof x !=== "undefined"' is going to throw. Any situations where it will would also break if you used var, but in much less obvious ways. "Is this variable reference before its variable declaration" is never a question that you would ever want to ask at runtime. I really don't think we'd be having this discussion if it had started with any statement other than "typeof x", but the function/operator (as we've tediously established) has no bearing on the behaviour exhibited. You have variables. It's illegal to refer to a variable before its been declared in it's lexical scope. Once declared, variables start with the value "undefined" until you assign them a value. I don't see what's massively complicated about that. Its the same as in many other languages, just replace "undefined" with "null". I have seen exactly zero blog posts about people being confused that they can't reference a variable before its been declared in other languages. I have seen dozens about people being confused by "variable hoisting". When looked at along with how it interacts with other language features, 'let' is definately less confusing than 'var'. |
|