I’m a bit confused about JavaScript’s undefined
and null
values.
What does if (!testvar)
actually do? Does it test for u
You cannot (should not?) define anything as undefined, as the variable would no longer be undefined – you just defined it to something.
You cannot (should not?) pass undefined
to a function. If you want to pass an empty value, use null
instead.
The statement if(!testvar)
checks for boolean true/false values, this particular one tests whether testvar
evaluates to false
. By definition, null
and undefined
shouldn't be evaluated neither as true
or false
, but JavaScript evaluates null
as false
, and gives an error if you try to evaluate an undefined variable.
To properly test for undefined
or null
, use these:
if(typeof(testvar) === "undefined") { ... }
if(testvar === null) { ... }