The quick answer is: it makes a difference if the person does not fill in and only call function ()
without passing parameter. In this case it will be undefined
. The null
must be explicitly assigned. The short version of the test would be
if (data != null) {
// Código
}
Complete answer
According to my answer in the question (What is the difference between null and undefined) [http://stackoverflow.com/a/2408/280] you can see that null
is an assigned value and means a object not instantiated, undefined
is something with unassigned value and represents a special value in Javascript, the absence of something in the variable. It indicates that a variable was never defined or that someone assigned undefined
to clear a variable. If you use typeof
you will see that the object indicates that it is of type "undefined"
.
var a;
console.log(typeof a); //resultado> "undefined"
console.log(typeof a === "object"); //resultado> false
console.log(typeof a === "undefined"); //resultado> true
console.log(typeof a == "undefined"); //resultado> true
null
is a null value assigned to an object. It is used to pass default values of uninitialized objects. If you use typeof
you will see that the object indicates that it is of type "object"
.
var a = null;
console.log(typeof a); //resultado> "object"
console.log(typeof a === "undefined"); //resultado> false
console.log(typeof a === null); //resultado> true
console.log(typeof a == null); //resultado> true
Most of the time you can test using ==
both undefined
and null
that will not make a difference, but if you want to make sure it's something that has not been assigned or if it's an empty object, you should check using ===
for the specific type. The simple comparison ( ==
) compares only the value and, if necessary, converts the value to the type (case of strings
and numbers) while the strict comparison ( ===
) compares type and value without converting it, if the type is not the same it returns false
. Here's how they behave between them:
console.log(false == undefined); //resultado> false
console.log(false == null); //resultado> false
console.log(null == undefined); //resultado> true
console.log(null === null); //resultado> true
console.log(undefined === undefined); //resultado> true
console.log(undefined === null); //resultado> false
console.log(undefined == null); //resultado> true
function test(val) {
return val == null;
}
test(null); //resultado > true
test(undefined); //resultado > true
You can take advantage of this difference as you are checking for parameters in functions and some of them are optional. Parameters that have not been passed will be undefined
and you can accept an empty object with null
. Here's an example:
function umaFuncao(primeiro, segundo, opcional) {
if (typeof opcional === "undefined") {
opcional = "três";
}
// faz algo
}