I've come across the following code:
function (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 rynah, 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 makingdata
an undefined variable, and raising an error ondata != null
.The function was called specifically with
null
(orundefined
), as its argument, in which casedata != null
already protects the inner code, rendering&& data !== undefined
useless.The function was called with a non-null argument, in which case it will trivially pass both
data != null
anddata !== undefined
.
Q: Am I 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 ifdata
variable evaluates to true.undefined
,null
, false, 0, empty string, empty array and (?)object with no properties evaluates to false, the rest is true. – J0HN May 21 at 14:40if(data)
would mean that he can't passfalse
or0
as values fordata
. – techfoobar May 21 at 14:41if(typeof someUndefVar == whatever) -- works
, andif(someUnderVar) -- error
. – afsantos May 21 at 14:42data !== null && data !== undefined
, which is equivalent todata != null
which 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 bothnull
andundefined
are being checked with the later two conditions. – zzzzBov May 21 at 15:52undefined
are 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
– Izkata May 21 at 18:32