How to test null values in Javascript

Asked

Viewed 44,155 times

21

I found the next code, and I got the impression that it didn’t make much sense.

function (data) {
    if (data != null && data !== undefined) {
        // codigo
    }
}

From here, three different scenarios can happen:

  • The function is called without arguments, making data an undeclared variable (and resulting in error when evaluating data != null).

  • The function was called specifically with argument null, or undefined, and in that case the condition data != null already protects the internal code, making the second condition irrelevant.

  • The function was called with a non-null argument, and in that passes the test, both conditions are true.

Is there any scenario where it makes sense to maintain the second condition?

  • 1

    does not forget to check data != ""

  • @alleen94 If I remember correctly, in this case the argument was supposed to be a object, but in the case of strings it is no doubt necessary to check the empty string.

4 answers

22


You’re right, it doesn’t make much sense. About each of the points you raised:

The function is called without arguments, making date an undeclared variable (and resulting in error when evaluating date != null).

There’s actually no such scenario. data is always stated within the function as it is a named argument. If you call the function without passing anything, it gets the value undefined.

The function was called specifically with argument null, or Undefined, and in this case the condition date != null already protects the internal code, making the second condition irrelevant.

Truth, data != null returns false if data for null or undefined (and only in such cases).

The function was called with a non-null argument, and in that passes the test, both conditions are true.

Right.

Is there any scenario where it makes sense to maintain the second condition?

No :) Unless you use strict equality operator ===, which considers types. With the ==, any comparison with null or undefined is true if the other side is also null or undefined. That is, they are interchangeable with ==. Therefore:

if (data !== null && data !== undefined)

is the same as:

if (data != null)

and the same as:

if (data != undefined)

5

One undeclared variable is different from having the value undefined.

Example of an undeclared variable:

var a;
alert(b); // ReferenceError: b is not defined

Example of a variable with the value undefined:

var a;
alert(a); // Escreve “undefined”

When a function is defined waiting for an argument, the variable that represents that argument is always stated, even if its value is undefined, and so the error situation never happens. However, it is right that data !== undefined after the test data != null is irrelevant and redundant.

The next example would make sense:

function (data) {
    // Ambos os testes com !==
    if (data !== null && data !== undefined) {
        // codigo
    }
}

Note that, by language specification, these two tests are abbreviated with one:

function (data) {
    if (data != null) {
        // codigo
    }
}
  • Javascript has no undeclared variable and this error. It will put the undeclared variable as global within window automatically, so that mistake will never happen.

  • 1

    @That’s only true in valuables to undeclared variables. Try using an undeclared variable in any other expression, such as a + 1, and you will see a Referenceerror.

  • Hmmm, I never found this error in Javascript, but I’ll see ... for me it has always been like undefined something undeclared.

  • @Alexandremarcondes It’s very simple to test, run this with the console open and you will see the error.

3

The quick answer is: it makes a difference if the person doesn’t fill in and just call function () without passing parameter. In this case it will be undefined. The null should be explicitly assigned. The short version of the test would be

if (data != null) {
    // Código
}

Full answer

According to my answer in the question (What is the difference between null and Undefined)[/a/2408/280] you can see that the null is an assigned value and means an instantiated object, already the undefined is something with an unassigned value and represents a special value in Javascript, the absence of something in the variable. It indicates that a variable has never been defined or that someone has assigned undefined to clear a variable. If you use typeof you will see that the object indicates to be of the 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

Already the nullis 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 to be of the 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 == so much for undefined how much for null which won’t make a difference, but if you want to make sure it’s something that hasn’t been assigned or if it’s an empty object you should check using === by the specific type. Simple comparison (==) compares only the value and, if necessary, converts the value to the type (case of strings and numbers) while strict comparison (===) compares the type and value, without converting it, if the type is not the same it returns false. See how they behave among themselves:

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 when checking by parameters in functions and some of them are optional. Parameters that have not been passed will be of value undefined and you can accept an empty object with null. Take an example:

function umaFuncao(primeiro, segundo, opcional) {
     if (typeof opcional === "undefined") {
        opcional = "três";
     }
    // faz algo
}
  • @bfavaretto really did not pay attention to such a fact.

1

It seems that it was not mentioned in the previous answers what values false, undefined, null, NaN , 0 , "", '' are values falsy in javascript, they are all the same thing false, explained by MDN.

And all other values are Truthy in javascript, ie are the same thing as true, also explained by MDN

Ex:

function (data) {
    if (data) { //Se data tiver um valor
        // codigo
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.