undefined
is a word that means not defined
.
null
is an object
Let see this code
function saySomething(thing) {
if(thing === undefined) {
sayRandomThing();
}else {
sayThat(thing);
}
}
In this case I would check if the argument is given or not or, in other words, if the argument is defined or not.
Note that the variable name thing
is declared, but it's not defined. So in this case thing === undefined
is enough and you don't need to do more verbose typeof thing === "undefined"
.
There is no reason to use the word null
. Because null
is an object and it have nothing to do with our thing
.
Just another note. typeof thing === "undefined"
is needed when effectly you don't know if the variable is declared. But, as documentation say:
However, this kind of technique should be avoided. JavaScript is a statically scoped language, so knowing if a variable is defined can be read by seeing whether it is defined in an enclosing context. The only exception is the global scope, but the global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object (using the in operator, for instance)
When should I use null
?
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
In APIs, null is often retrieved in place where an object can be expected but no object is relevant.
null
is an object. Javascript core use null
when a function should returns an object or an array, but in some case should tell us an "object not found" (different case of an empty object {}
that means: I've found the object, it's empty). It's the case of method match
for example.
var matches = "My awesome string".match("don't match anything");
console.log(matches === null); // true
In your script, you know, as developer, what type should be the variable. And you should know which condition you should use. Remembering:
- If you don't know if the variable is declared or not, use
if(typeof varName === "undefined")
before other checks.
- If you don't know if the variable is defined or not, use
if(varName === undefined)
before other checks.
- If you know if the variable is defined and it's an object, check if is null with
if(varName === null)
The strict equality operator (===
) is needed because varName == undefined
also checks whether varName
is null