getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
Other
177.97k stars 33.41k forks source link

Chapter 2: Illustrating Lexical Scope (2nd Edition) - Undeclared variables safe to use in typeof statements #1709

Closed OliverSieweke closed 3 years ago

OliverSieweke commented 3 years ago

Please type "I already searched for this issue": I already searched for this issue.

Edition: (1st or 2nd) 2nd

Book Title: Scope & Closures

Chapter: Chapter 2: Illustrating Lexical Scope

Section Title: Undefined Mess

Problem: The Undefined Mess section states:

If the variable is a source, an unresolved identifier lookup is considered an undeclared (unknown, missing) variable, which always results in a ReferenceError being thrown.

I believe that this sentence is not strictly correct. It is indeed safe to use undeclared variables in the case of typeof statements without causing a ReferenceError, as is actually shown in one of the provided examples:

typeof doesntExist;     // "undefined"

Thanks for making this material available. I very much appreciate the tone in the second edition!

getify commented 3 years ago

That's true. I just didn't care to delve into those weeds at that point.

Also, you shouldn't really ever use typeof against a variable that you don't know if exists or not... except in one narrow corner case: when dealing with global variables that may or may not have been declared in other script files. This used to be a more common pattern, but the language is definitely moving away from it, so it's not a top-of-mind kind of thing anymore.

At best I might have noted this nuance in the appendix, but it just didn't feel weighty enough of an exception to get into.

Thanks!

OliverSieweke commented 3 years ago

Thanks for the clarifications! I hope the rest of the series is coming along well!