I've come across the following code:
function test(data) {
if (data != null && data !== undefined) {
// some code here
}
}
I'm somewhat new to JavaScript, but, from other questions I've been reading here, I'm under the impression that this code does not make much sense.
You'll get an error if you access an undefined variable in any context other thantypeof.
Update: The (quote of the) answer above may be misleading. It should say «an undeclared variable», instead of «an undefined variable».
As I found out, in the answers by Ryan ♦, maerics, and nwellnhof, even when no arguments are provided to a function, its variables for the arguments are always declared. This fact also proves wrong the first item in the list below.
From my understanding, the following scenarios may be experienced:
The function was called with no arguments, thus makingdataan undefined variable, and raising an error ondata != null.The function was called specifically with
null(orundefined), as its argument, in which casedata != nullalready protects the inner code, rendering&& data !== undefineduseless.The function was called with a non-null argument, in which case it will trivially pass both
data != nullanddata !== undefined.
Q: Is my understanding correct?
I've tried the following, in Firefox's console:
--
[15:31:31.057] false != null
[15:31:31.061] true
--
[15:31:37.985] false !== undefined
[15:31:37.989] true
--
[15:32:59.934] null != null
[15:32:59.937] false
--
[15:33:05.221] undefined != null
[15:33:05.225] false
--
[15:35:12.231] "" != null
[15:35:12.235] true
--
[15:35:19.214] "" !== undefined
[15:35:19.218] true
I can't figure out a case where the data !== undefined after data != null might be of any use.



if (data). It's mnemonic Javascript way to check ifdatavariable evaluates to true.undefined,null, false, 0, empty string, empty array and (?)object with no properties evaluates to false, the rest is true.if(data)would mean that he can't passfalseor0as values fordata.if(typeof someUndefVar == whatever) -- works, andif(someUnderVar) -- error.data !== null && data !== undefined, which is equivalent todata != nullwhich is equivalent todata != undefined. The former form tends to be favored as it's more explicit about the conditions, whereas it'd be easy to overlook that bothnullandundefinedare being checked with the later two conditions.undefinedare IMO a code smell. It's not a protected keyword likenull, it's a variable that happens to be undefined. This is completely valid and is going to break your code:undefined = 1