Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does underscore's _.isUndefined(variable) give an error that variable is not defined?

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.

like image 869
Jami Avatar asked Jan 29 '13 19:01

Jami


1 Answers

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.

typeof is special in that it works similar to a try..catch around getting the variable, and returning "undefined" in the catch. Non-native code (such as isUndefined) 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:

function test(param) {
    console.log(_.isUndefined(param));
}
test("argument");
test(); // undefined argument

Or another example:

function test() {
    console.log(_.isUndefined(foo)); // true, no error due to hoisting
    var foo = 3;
    console.log(_.isUndefined(foo)); // false, foo is defined now.
}

You can also specify an explicit source, such as window.targetNode. window is defined, so the script knows where to look, however the targetNode property may not be defined, in which case you get undefined.

like image 167
Niet the Dark Absol Avatar answered Oct 24 '22 22:10

Niet the Dark Absol