How to test null values in JavaScript

17

I found the following code, and I got the impression that it did not 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 evaluating data != null ).

  • The function was specifically called with argument null , or undefined , in which case the data != null condition 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 a scenario where it makes sense to keep the second condition?

    
asked by anonymous 25.02.2014 / 22:34

5 answers

18

You're right, it does not make much sense. On each of the points you raised:

  

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

Actually, there is no such scenario. data is always declared inside the function, since it is a named argument. If you call the function without passing anything, it gets the value undefined .

  

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

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

  

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

Right.

  

Is there a scenario where it makes sense to keep the second condition?

No :) Unless you use strict equality operator === , which considers types. With == , 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)
    
25.02.2014 / 22:38
5

An 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 expecting an argument, the variable representing this argument is always declared, even if its value is undefined , so the error situation never occurs. However, it is certain that% of% after the% test of% is irrelevant and redundant.

The following example would already make sense:

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

Note that by specifying the language, these two tests are abbreviated with just one:

function (data) {
    if (data != null) {
        // codigo
    }
}
    
25.02.2014 / 22:34
2

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
}
    
25.02.2014 / 23:13
1

It seems that it has not been mentioned in the previous answers that values false , undefined , null , NaN , 0 , "" , '' in javascript, they are all the same as false , explained by MDN . p>

And all other values are truthy in javascript, meaning they are the same as true , also explained by MDN

Ex:

function (data) {
    if (data) { //Se data tiver um valor
        // codigo
    }
}
    
14.03.2017 / 11:38
-1

The keywords "null" and "undefined" represent "states" rather than "values". Thus, the way of checking for a state of a variable will depend on the situation and the context in which it is sought to verify, since the state of any variable is not always to be verified through the explicit use of the respective keywords, but also through a based on its current value. As an example, note the simplistic code below (it's simple but absolutely pertinent to the question raised):

<script type="text/javascript">
    var name;
    name = window.prompt("Please enter your name");

    if (name != "null") {
        document.writeln("<h1>Helo, " + name + ", welcome to JavaScript programming</h1>"); 
    }else{
        document.writeln("<h1>Helo, Novato, welcome to JavaScript programming</h1>");
    }
</script>

It is known that the prompt function always returns a string, either specified or not by the user (this is so at least when run in Chrome or Firefox). So, in the above situation, if the user does not specify any value and click OK, the prompt function will return the literal "", and so the if block will be executed. If the user clicks Cancel, the prompt function will return the literal "null" (as a result of an internal check where the absence of value, ie a state strong> empty), and the else block will be executed. If the user specifies something, the prompt function will return the user-specified value (as long as it does not specify a "null" literal, of course), so the if block will be executed. Therefore (this is where the question is), in this specific situation, the test is performed by checking the correspondence between the contents of the name variable and the literal value "null" returned by the prompt function. Now, for your case, you have to specifically check what the content (type and value) of your data variable is, so on top of that decide how you will compose your test. The meaning of a code (and the way we deal with it) will always depend on its context of use.

    
13.03.2017 / 03:03