[javascript] How to check for an undefined or null variable in JavaScript?

We are frequently using the following code pattern in our JavaScript code

if (typeof(some_variable) != 'undefined' && some_variable != null)
{
    // Do something with some_variable
}

Is there a less verbose way of checking that has the same effect?

According to some forums and literature saying simply the following should have the same effect.

if (some_variable)
{
    // Do something with some_variable
}

Unfortunately, Firebug evaluates such a statement as error on runtime when some_variable is undefined, whereas the first one is just fine for it. Is this only an (unwanted) behavior of Firebug or is there really some difference between those two ways?

This question is related to javascript null undefined

The answer is


I think the most efficient way to test for "value is null or undefined" is

if ( some_variable == null ){
  // some_variable is either null or undefined
}

So these two lines are equivalent:

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}

Note 1

As mentioned in the question, the short variant requires that some_variable has been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:

check for optional arguments:

function(foo){
    if( foo == null ) {...}

check for properties on an existing object

if(my_obj.foo == null) {...}

On the other hand typeof can deal with undeclared global variables (simply returns undefined). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.

Note 2

This - even shorter - variant is not equivalent:

if ( !some_variable ) {
  // some_variable is either null, undefined, 0, NaN, false, or an empty string
}

so

if ( some_variable ) {
  // we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}

Note 3

In general it is recommended to use === instead of ==. The proposed solution is an exception to this rule. The JSHint syntax checker even provides the eqnull option for this reason.

From the jQuery style guide:

Strict equality checks (===) should be used in favor of ==. The only exception is when checking for undefined and null by way of null.

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

In order to understand, Let's analyze what will be the value return by the Javascript Engine when converting undefined , null and ''(An empty string also). You can directly check the same on your developer console.

enter image description here

You can see all are converting to false , means All these three are assuming ‘lack of existence’ by javascript. So you no need to explicitly check all the three in your code like below.

if (a === undefined || a === null || a==='') {
    console.log("Nothing");
} else {
    console.log("Something");
}

Also I want to point out one more thing.

What will be the result of Boolean(0)?

Of course false. This will create a bug in your code when 0 is a valid value in your expected result. So please make sure you check for this when you write the code.


I have done this using this method

save the id in some variable

var someVariable = document.getElementById("someId");

then use if condition

if(someVariable === ""){
 //logic
} else if(someVariable !== ""){
 //logic
}

Firstly you have to be very clear about what you test. JavaScript has all sorts of implicit conversions to trip you up, and two different types of equality comparator: == and ===.

A function, test(val) that tests for null or undefined should have the following characteristics:

 test(null)         => true
 test(undefined)    => true
 test(0)            => false
 test(1)            => false
 test(true)         => false
 test(false)        => false
 test('s')          => false
 test([])           => false

Let's see which of the ideas here actually pass our test.

These work:

val == null
val === null || val === undefined
typeof(val) == 'undefined' || val == null
typeof(val) === 'undefined' || val === null

These do not work:

typeof(val) === 'undefined'
!!val

I created a jsperf entry to compare the correctness and performance of these approaches. Results are inconclusive for the time being as there haven't been enough runs across different browsers/platforms. Please take a minute to run the test on your computer!

At present, it seems that the simple val == null test gives the best performance. It's also pretty much the shortest. The test may be negated to val != null if you want the complement.


this is the only case in which == and != should be used:

if (val == null) console.log('val is null or undefined')
if (val != null) console.log('val is neither null nor undefined')

For any other comparisons, the strict comparators (=== and !==) should be used.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness


If the purpose of the if statement is to check for null or undefined values before assigning a value to a variable, you can make use of the Nullish Coalescing Operator. According to the data from caniuse, it should be supported by around 85% of the browsers(as of January 2021). An example of the operator is shown below:

const a = some_variable ?? '';

This will ensure that the variable will be assigned to an empty string (or any other default value) if some_variable is null or undefined.

This operator is most suited for your use case, as it does not return the default value for other types of falsy value such as 0 and ''.


here's another way using the Array includes() method:

[undefined, null].includes(value)

Checking null with normal equality will also return true for undefined.

if (window.variable == null) alert('variable is null or undefined');

JS Equality


If you try and reference an undeclared variable, an error will be thrown in all JavaScript implementations.

Properties of objects aren't subject to the same conditions. If an object property hasn't been defined, an error won't be thrown if you try and access it. So in this situation you could shorten:

 if (typeof(myObj.some_property) != "undefined" && myObj.some_property != null)

to

if (myObj.some_property != null)

With this in mind, and the fact that global variables are accessible as properties of the global object (window in the case of a browser), you can use the following for global variables:

if (window.some_variable != null) {
    // Do something with some_variable
}

In local scopes, it always useful to make sure variables are declared at the top of your code block, this will save on recurring uses of typeof.


This is an example of a very rare occasion where it is recommended to use == instead of ===. Expression somevar == null will return true for undefined and null, but false for everything else (an error if variable is undeclared).

Using the != will flip the result, as expected.

Modern editors will not warn for using == or != operator with null, as this is almost always the desired behavior.

Most common comparisions:

undeffinedVar == null     // true
obj.undefinedProp == null // true
null == null              // true
0 == null                 // false
'0' == null               // false
'' == null                // false

Try it yourself:

let undefinedVar;
console.table([
    { test : undefinedVar,     result: undefinedVar     == null },
    { test : {}.undefinedProp, result: {}.undefinedProp == null },
    { test : null,             result: null             == null },
    { test : false,            result: false            == null },
    { test : 0,                result: 0                == null },
    { test : '',               result: ''               == null },
    { test : '0',              result: '0'              == null },
]);

Open the Developer tools in your browser and just try the code shown in the below image.

Img1 Img2


Testing nullity (if (value == null)) or non-nullity (if (value != null)) is less verbose than testing the definition status of a variable.

Moreover, testing if (value) (or if( obj.property)) to ensure the existence of your variable (or object property) fails if it is defined with a boolean false value. Caveat emptor :)


whatever yyy is undefined or null, it will return true

if (typeof yyy == 'undefined' || !yyy) {
    console.log('yes');
} else {
    console.log('no');
}

yes

if (!(typeof yyy == 'undefined' || !yyy)) {
    console.log('yes');
} else {
    console.log('no');
}

no


With Ramda, you can simply do R.isNil(yourValue) Lodash and other helper libraries have the same function.


Both values can be easily distinguished by using the strict comparison operator:

Working example at:

http://www.thesstech.com/tryme?filename=nullandundefined

Sample Code:

function compare(){
    var a = null; //variable assigned null value
    var b;  // undefined
    if (a === b){
        document.write("a and b have same datatype.");
    }
    else{
        document.write("a and b have different datatype.");
    }   
}

In newer JavaScript standards like ES5 and ES6 you can just say

> Boolean(0) //false
> Boolean(null)  //false
> Boolean(undefined) //false

all return false, which is similar to Python's check of empty variables. So if you want to write conditional logic around a variable, just say

if (Boolean(myvar)){
   // Do something
}

here "null" or "empty string" or "undefined" will be handled efficiently.


Since there is no single complete and correct answer, I will try to summarize:

In general, the expression:

if (typeof(variable) != "undefined" && variable != null)

cannot be simplified, because the variable might be undeclared so omitting the typeof(variable) != "undefined" would result in ReferenceError. But, you can simplify the expression according to the context:

If the variable is global, you can simplify to:

if (window.variable != null)

If it is local, you can probably avoid situations when this variable is undeclared, and also simplify to:

if (variable != null)

If it is object property, you don't have to worry about ReferenceError:

if (obj.property != null)

As mentioned in one of the answers, you can be in luck if you are talking about a variable that has a global scope. As you might know, the variables that you define globally tend to get added to the windows object. You can take advantage of this fact so lets say you are accessing a variable called bleh, just use the double inverted operator (!!)

!!window['bleh'];

This would return a false while bleh has not been declared AND assigned a value.


In ES5 or ES6 if you need check it several times you cand do:

_x000D_
_x000D_
const excluded = [null, undefined, ''];_x000D_
_x000D_
if (!exluded.includes(varToCheck) {_x000D_
  // it will bee not null, not undefined and not void string_x000D_
}
_x000D_
_x000D_
_x000D_


Best way to compare undefined or null or 0 with ES5 and ES6 standards

 if ((Boolean(some_variable_1) && Boolean(some_variable_2)) === false) {
    // do something
    }

You must define a function of this form:

validate = function(some_variable){
    return(typeof(some_variable) != 'undefined' && some_variable != null)
}

You can just check if the variable has a value or not. Meaning,

if( myVariable ) {
//mayVariable is not :
//null
//undefined
//NaN
//empty string ("")
//0
//false

}

If you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. e.g.

if( typeof myVariable !== 'undefined' ) {
    // myVariable will get resolved and it is defined
}

Similar to what you have, you could do something like

if (some_variable === undefined || some_variable === null) { do stuff }


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