If you define a variable like this:
var defined;
It has no value, but you don't get a ReferenceError, because the reference exists. It just doesn't reference anything. Thus, the following is valid.
if (defined != null) { ... }
In the case of a function, such as this
function doSomethingWithDefined(defined) {
if (defined != null) { ... }
}
It can be translated to:
function doSomethingWithDefined() {
var defined = arguments[0];
if (defined != null) { ... }
}
Because the variable is declared implicitly (but not necessarily defined), you can do this and not get an exception, so there's no need for typeof
.
doSomethingWithDefined("value"); // passes defined != null
doSomethingWithDefined(); // defined == null, but no exception is thrown
The typeof operator is usually used when you're not sure if a variable has been declared. However there is an alternative that works for all real world scenarios.
if (window.myvariable != null) {
// do something
}
Because global variables are the only non-parameter variables you should be concerned about, using property access we can also avoid the exception.
That said, I strongly recommend type checking, rather than type avoiding. Be positive!
Is it a string?
if (typeof declared === "string"){ ... }
Is it an array?
if (typeof declared === "object" && declared.length != null){ ... }
Is it a non-array object?
if (typeof declared === "object" && declared.length == null){ ... }
Is it a function?
if (typeof declared === "function"){ ... }