It can be difficult to decide whether you should be checking for null
or undefined
in JavaScript; on the face of things it may seem that they do the same job.
Fortunately, there’s quite an easy to follow rule with this; unless you specifically set something to null
, you should most likely be checking for undefined.
As ever there are exceptions, and here it is; if using document.getElementById()
, null
; is returned if no element could be found.
Let’s go through some situations where things will be undefined
:
-
Checking a variables default value. An un-initialized variable will be
undefined
. Caveat though; if a variable is undeclared, this will throw an error.var foo; alert(foo === undefined); // true alert(bar === undefined); // error
-
The default return value of a function.
function foo() { } function bar() { return; } alert(foo() === undefined); // true alert(bar() === undefined); // true
-
The value of an unspecified attribute in an Object
var obj = {}; alert(obj.foo === undefined); // true
-
The value of an out-of-bounds array index
var array = []; alert(array[100] === undefined); // true
However, should you really be checking against undefined
, are there any caveats of doing so? It turns out there is!
- As mentioned above, comparing an undeclared variable against
undefined
will throw aReferenceError: foo is not defined
. -
undefined
is a property on the global object. Prior to ES5, this value was writable; allowing problems like this;var foo; undefined = 42; alert(foo === undefined); // false alert(42 === undefined); // true
To avoid these caveats, it turns out you should use the typeof
operator instead, and compare against the Undefined
type:
var foo;
undefined = 42;
alert(typeof foo === "undefined"); // true
alert(typeof 42 === "undefined"); // false
alert(typeof bar === "undefined"); // true- no error!
what’s the difference between == and === in js ? Is it the same as in php?
Yes it is,
==
will attempt to convert the operands to the same type before applying a strict comparison, where-as===
will perform no conversion. You can see a more detailed explanation on the MDC site!