how to check for an undefined or null variable in javascript

how to check for an undefined or null variable in javascript  using -'javascript,null,undefined'

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?

asked Oct 11, 2015 by loknath.ganji
0 votes

10 Answers

0 votes

You have to differentiate between two cases

1) Undefined variables , like 'foo'. You'll get an error if you access an undefined variable in any context other than typeof.

  if(typeof someUndefVar == whatever) -- works
  if(someUndefVar) -- error  

So, for variables, the typeof check is a must. On the other side, it's only rarely needed - you usually know if your variables are defined or not.

2) Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns "undefined", which, when converted to boolean, evaluates to false. So, if you don't care about '0' and 'false', if(obj.undefProp) is ok. There's a common idiom based on this fact:

 value = obj.prop || defaultValue

which means "if obj has a prop, use that, otherwise default".

Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using in operator instead

 value = ('prop' in obj) ? obj.prop : defaultValue
answered Oct 11, 2015 by ashishshukla
0 votes

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:

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

check for properties on an existing object

if( == 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


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;
answered Oct 11, 2015 by sameer rathore
0 votes

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)


if (myObj.some_property)

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) {
    // 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.

answered Oct 11, 2015 by vijayshukla80
0 votes

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'

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.

answered Oct 11, 2015 by badhwar.rohit
0 votes

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 (!!)


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

answered Oct 11, 2015 by suyesh.lokhande
0 votes

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 ( != null)
answered Oct 11, 2015 by ankitarajoria4
0 votes

You must define a function of this form:

validate = function(some_variable){
    return(typeof(some_variable) != 'undefined' && some_variable != null)
answered Oct 11, 2015 by dhananjayksharma
0 votes

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( to ensure the existence of your variable (or object property) fails if it is defined with a boolean false value. Caveat emptor :)

answered Oct 11, 2015 by pradip.bhoge
0 votes

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

Working example at:

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.");
        document.write("a and b have different datatype.");
answered Oct 11, 2015 by amit.gupta
0 votes

You should never have to check for typeof myVar != "undefined". If you try to reference an undeclared variable, something should be wrong in your code and an exception should be fired. Undeclared variables are a very bad thing in javascript, because of a few things, like:

  1. They pollute the global namespace, ie. window
  2. They can easily collide inside this namespace
  3. They are not garbage-collected before the window closes
  4. They require security tests like typeof myVar != "undefined"

So declare your variables and treat undefined and null like two distinct values, because 4 different things can happen with a variable:

  1. When a variable is not defined and you try to know its value, javascript throws a ReferenceError exception (is not defined). That's a bad thing, ergo the exception.
  2. undefined means that the variable value has not been defined. So the variable value is unknown ; it is not known if the variable has a value and what it is.
  3. null means that the variable value, which is defined, is null. So the variable has no value ; it is known that the variable doesn't have a value.
  4. Else, you have a value, enjoy!
answered Oct 11, 2015 by mannumits1