In Chrome, I’m getting “Uncaught ReferenceError: targetNode is not defined” from this line of code console.log(_.isUndefined(targetNode));.
I get the same error when I do console.log(targetNode === void(0)); and console.log(targetNode);.
typeof targetNode === "undefined" returns true as expected, but my understanding is that the void(0) comparison is more efficient.
I can get around this by setting a default for targetNode or I can just use typeof targetNode === "undefined", but I’m trying to understand why a test for whether a variable is undefined would choke if the variable is undefined.
When you ask for
targetNode, it looks for a local variable, then in subsequent parent scopes until it reaches the end of the chain. If it still hasn’t found it, there’s an error.typeofis special in that it works similar to atry..catcharound getting the variable, and returning"undefined"in the catch. Non-native code (such asisUndefined) can’t do that since the variable must be resolved in order to pass it to the function.However, if the symbol is defined, it can be validly passed. For example:
Or another example:
You can also specify an explicit source, such as
window.targetNode.windowis defined, so the script knows where to look, however thetargetNodeproperty may not be defined, in which case you getundefined.