[javascript] JavaScript null check

I've come across the following code:

function test(data) {
    if (data != null && data !== undefined) {
        // some code here
    }
}

I'm somewhat new to JavaScript, but, from other questions I've been reading here, I'm under the impression that this code does not make much sense.


In particular, this answer states that

You'll get an error if you access an undefined variable in any context other than typeof.

Update: The (quote of the) answer above may be misleading. It should say «an undeclared variable», instead of «an undefined variable».

As I found out, in the answers by Ryan ?, maerics, and nwellnhof, even when no arguments are provided to a function, its variables for the arguments are always declared. This fact also proves wrong the first item in the list below.


From my understanding, the following scenarios may be experienced:

  • The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.

  • The function was called specifically with null (or undefined), as its argument, in which case data != null already protects the inner code, rendering && data !== undefined useless.

  • The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.

Q: Is my understanding correct?


I've tried the following, in Firefox's console:

--
[15:31:31.057] false != null
[15:31:31.061] true
--
[15:31:37.985] false !== undefined
[15:31:37.989] true
--
[15:32:59.934] null != null
[15:32:59.937] false
--
[15:33:05.221] undefined != null
[15:33:05.225] false
--
[15:35:12.231] "" != null
[15:35:12.235] true
--
[15:35:19.214] "" !== undefined
[15:35:19.218] true

I can't figure out a case where the data !== undefined after data != null might be of any use.

This question is related to javascript null undefined null-check

The answer is


In JavaScript, null is a special singleton object which is helpful for signaling "no value". You can test for it by comparison and, as usual in JavaScript, it's a good practice to use the === operator to avoid confusing type coercion:

var a = null;
alert(a === null); // true

As @rynah mentions, "undefined" is a bit confusing in JavaScript. However, it's always safe to test if the typeof(x) is the string "undefined", even if "x" is not a declared variable:

alert(typeof(x) === 'undefined'); // true

Also, variables can have the "undefined value" if they are not initialized:

var y;
alert(typeof(y) === 'undefined'); // true

Putting it all together, your check should look like this:

if ((typeof(data) !== 'undefined') && (data !== null)) {
  // ...

However, since the variable "data" is always defined since it is a formal function parameter, using the "typeof" operator is unnecessary and you can safely compare directly with the "undefined value".

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

This snippet amounts to saying "if the function was called with an argument which is defined and is not null..."


I think, testing variables for values you do not expect is not a good idea in general. Because the test as your you can consider as writing a blacklist of forbidden values. But what if you forget to list all the forbidden values? Someone, even you, can crack your code with passing an unexpected value. So a more appropriate approach is something like whitelisting - testing variables only for the expected values, not unexpected. For example, if you expect the data value to be a string, instead of this:

function (data) {
  if (data != null && data !== undefined) {
    // some code here
    // but what if data === false?
    // or data === '' - empty string?
  }
}

do something like this:

function (data) {
  if (typeof data === 'string' && data.length) {
    // consume string here, it is here for sure
    // cleaner, it is obvious what type you expect
    // safer, less error prone due to implicit coercion
  } 
}

var a;
alert(a); //Value is undefined

var b = "Volvo"; 
alert(b); //Value is Volvo

var c = null;
alert(c); //Value is null

typeof foo === "undefined" is different from foo === undefined, never confuse them. typeof foo === "undefined" is what you really need. Also, use !== in place of !=

So the statement can be written as

function (data) {
  if (typeof data !== "undefined" && data !== null) {
    // some code here
  }
}

Edit:

You can not use foo === undefined for undeclared variables.

var t1;

if(typeof t1 === "undefined")
{
  alert("cp1");
}

if(t1 === undefined)
{
  alert("cp2");
}

if(typeof t2 === "undefined")
{
  alert("cp3");
}

if(t2 === undefined) // fails as t2 is never declared
{
  alert("cp4");
}

Q: The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.

A: Yes, data will be set to undefined. See section 10.5 Declaration Binding Instantiation of the spec. But accessing an undefined value does not raise an error. You're probably confusing this with accessing an undeclared variable in strict mode which does raise an error.

Q: The function was called specifically with null (or undefined), as its argument, in which case data != null already protects the inner code, rendering && data !== undefined useless.

Q: The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.

A: Correct. Note that the following tests are equivalent:

data != null
data != undefined
data !== null && data !== undefined

See section 11.9.3 The Abstract Equality Comparison Algorithm and section 11.9.6 The Strict Equality Comparison Algorithm of the spec.


The simple way to do your test is :

function (data) {
    if (data) { // check if null, undefined, empty ...
        // some code here
    }
}

In your case use data==null (which is true ONLY for null and undefined - on second picture focus on rows/columns null-undefined)

_x000D_
_x000D_
function test(data) {_x000D_
    if (data != null) {_x000D_
        console.log('Data: ', data);_x000D_
    }_x000D_
}_x000D_
_x000D_
test();          // the data=undefined_x000D_
test(null);      // the data=null_x000D_
test(undefined); // the data=undefined_x000D_
_x000D_
test(0); _x000D_
test(false); _x000D_
test('something');
_x000D_
_x000D_
_x000D_

Here you have all (src):

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to null

getElementById in React Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? How to resolve TypeError: Cannot convert undefined or null to object Check if returned value is not null and if so assign it, in one line, with one method call How do I assign a null value to a variable in PowerShell? Using COALESCE to handle NULL values in PostgreSQL How to check a Long for null in java Check if AJAX response data is empty/blank/null/undefined/0 Best way to check for "empty or null value"

Examples related to undefined

Checking for Undefined In React Raw_Input() Is Not Defined How to resolve TypeError: Cannot convert undefined or null to object "undefined" function declared in another file? Passing Variable through JavaScript from one html page to another page Javascript - removing undefined fields from an object PHP How to fix Notice: Undefined variable: Undefined Symbols for architecture x86_64: Compiling problems Undefined or null for AngularJS PHP Notice: Undefined offset: 1 with array when reading data

Examples related to null-check

Is there a way to check for both `null` and `undefined`? Java Object Null Check for method JavaScript null check Null or empty check for a string variable How to check if a variable is not null?