How can I determine if a variable is 'undefined' or 'null'?

JavascriptJqueryVariablesNullUndefined

Javascript Problem Overview


How do I determine if variable is undefined or null?

My code is as follows:

var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
  // DO SOMETHING
};

<div id="esd-names">
  <div id="name"></div>
</div>

But if I do this, the JavaScript interpreter halts execution.

Javascript Solutions


Solution 1 - Javascript

You can use the qualities of the abstract equality operator to do this:

if (variable == null){
    // your code here.
}

Because null == undefined is true, the above code will catch both null and undefined.

Solution 2 - Javascript

The standard way to catch null and undefined simultaneously is this:

if (variable == null) {
     // do something 
}

--which is 100% equivalent to the more explicit but less concise:

if (variable === undefined || variable === null) {
     // do something 
}

When writing professional JS, it's taken for granted that type equality and the behavior of == vs === is understood. Therefore we use == and only compare to null.


Edit again

The comments suggesting the use of typeof are simply wrong. Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages. Use try/catch if you are working with input you don't have control over.

You should not have any references to undeclared variables in your code.

Solution 3 - Javascript

Combining the above answers, it seems the most complete answer would be:

if( typeof variable === 'undefined' || variable === null ){
    // Do stuff
}

This should work for any variable that is either undeclared or declared and explicitly set to null or undefined. The boolean expression should evaluate to false for any declared variable that has an actual non-null value.

Solution 4 - Javascript

if (variable == null) {
    // Do stuff, will only match null or undefined, this won't match false
}

Solution 5 - Javascript

if (typeof EmpName != 'undefined' && EmpName) {

will evaluate to true if value is not:

  • null

  • undefined

  • NaN

  • empty string ("")

  • 0

  • false

Solution 6 - Javascript

Probably the shortest way to do this is:

if(EmpName == null) { /* DO SOMETHING */ };

Here is proof:

function check(EmpName) {
  if(EmpName == null) { return true; };
  return false;
}

var log = (t,a) => console.log(`${t} -> ${check(a)}`);

log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");

// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined" 

And here are more details about == (source here)

Enter image description here

BONUS: reason why === is more clear than == (look on agc answer)

Enter image description here

Solution 7 - Javascript

jQuery attr() function returns either a blank string or the actual value (and never null or undefined). The only time it returns undefined is when your selector didn't return any element.

So you may want to test against a blank string. Alternatively, since blank strings, null and undefined are false-y, you can just do this:

if (!EmpName) { //do something }

Solution 8 - Javascript

Edited answer: In my opinion, you shouldn't use the function from my below old answer. Instead, you should probably know the type of your variable and use the according to check directly (for example, wondering if an array is empty? just do if(arr.length===0){} etc.). This answer doesn't even answer OP's question.


I've come to write my own function for this. JavaScript is weird.

It is usable on literally anything. (Note that this also checks if the variable contains any usable values. But since this information is usually also needed, I think it's worth posting). Please consider leaving a note.

function empty(v) {
    let type = typeof v;
    if (type === 'undefined') {
        return true;
    }
    if (type === 'boolean') {
        return !v;
    }
    if (v === null) {
        return true;
    }
    if (v === undefined) {
        return true;
    }
    if (v instanceof Array) {
        if (v.length < 1) {
            return true;
        }
    } else if (type === 'string') {
        if (v.length < 1) {
            return true;
        }
        if (v === '0') {
            return true;
        }
    } else if (type === 'object') {
        if (Object.keys(v).length < 1) {
            return true;
        }
    } else if (type === 'number') {
        if (v === 0) {
            return true;
        }
    }
    return false;
}

TypeScript-compatible.


This function should do exactly the same thing like PHP's empty() function (see RETURN VALUES)

Considers undefined, null, false, 0, 0.0, "0" {}, [] as empty.

"0.0", NaN, " ", true are considered non-empty.

Solution 9 - Javascript

The shortest and easiest:

if(!EmpName ){
 // DO SOMETHING
}

this will evaluate true if EmpName is:

  • null
  • undefined
  • NaN
  • empty
  • string ("")
  • 0
  • false

Solution 10 - Javascript

If the variable you want to check is a global, do

if (window.yourVarName) {
    // Your code here
}

This way to check will not throw an error even if the yourVarName variable doesn't exist.

Example: I want to know if my browser supports History API

if (window.history) {
    history.back();
}

How this works:

window is an object which holds all global variables as its properties, and in JavaScript it is legal to try to access a non-existing object property. If history doesn't exist then window.history returns undefined. undefined is falsey, so code in an if(undefined){} block won't run.

Solution 11 - Javascript

In JavaScript, as per my knowledge, we can check an undefined, null or empty variable like below.

if (variable === undefined){
}

if (variable === null){
}

if (variable === ''){
}

Check all conditions:

if(variable === undefined || variable === null || variable === ''){
}

Solution 12 - Javascript

Since you are using jQuery, you can determine whether a variable is undefined or its value is null by using a single function.

var s; // undefined
jQuery.isEmptyObject(s); // will return true;
 
s = null; // defined as null
jQuery.isEmptyObject(s); // will return true;

// usage
if(jQuery.isEmptyObject(s)){
    alert('Either variable: s is undefined or its value is null');
}else{
     alert('variable: s has value ' + s);
}

s = 'something'; // defined with some value
jQuery.isEmptyObject(s); // will return false;

Solution 13 - Javascript

I've just had this problem i.e. checking if an object is null.
I simply use this:

if (object) {
    // Your code
}

For example:

if (document.getElementById("enterJob")) {
    document.getElementById("enterJob").className += ' current';
}

Solution 14 - Javascript

You can simply use the following (I know there are shorter ways to do this, but this may make it easier to visually observe, at least for others looking at the code).

if (x === null || x === undefined) {
 // Add your response code here, etc.
}

source: https://www.growthsnippets.com/how-can-i-determine-if-a-variable-is-undefined-or-null/

Solution 15 - Javascript

jQuery check element not null:

var dvElement = $('#dvElement');

if (dvElement.length  > 0) {
    // Do something
}
else{
    // Else do something else
}

Solution 16 - Javascript

The easiest way to check is:

if(!variable) {
  // If the variable is null or undefined then execution of code will enter here.
}

Solution 17 - Javascript

With the newest javascript changes, you can use the new logical operator ??= to check if the left operand is null or undefined and if so assign the value of right operand.

SO,

if(EmpName == null){  // if Variable EmpName null or undefined
  EmpName = 'some value';
};

Is equivalent to:

EmpName ??= 'some value';

Solution 18 - Javascript

I run this test in the Chrome console. Using (void 0) you can check undefined:

var c;
undefined
if (c === void 0) alert();
// output =  undefined
var c = 1;
// output =  undefined
if (c === void 0) alert();
// output =   undefined
// check c value  c
// output =  1
if (c === void 0) alert();
// output =  undefined
c = undefined;
// output =  undefined
if (c === void 0) alert();
// output =   undefined

Solution 19 - Javascript

To test if a variable is null or undefined I use the below code.

    if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
      console.log('variable is undefined or null');
    }

Solution 20 - Javascript

With the solution below:

const getType = (val) => typeof val === 'undefined' || !val ? null : typeof val;
const isDeepEqual = (a, b) => getType(a) === getType(b);

console.log(isDeepEqual(1, 1)); // true
console.log(isDeepEqual(null, null)); // true
console.log(isDeepEqual([], [])); // true
console.log(isDeepEqual(1, "1")); // false
etc...

I'm able to check for the following:

  • null
  • undefined
  • NaN
  • empty
  • string ("")
  • 0
  • false

Solution 21 - Javascript

if you create a function to check it:

export function isEmpty (v) {
 if (typeof v === "undefined") {
   return true;
 }
 if (v === null) {
   return true;
 }
 if (typeof v === "object" && Object.keys(v).length === 0) {
   return true;
 }

 if (Array.isArray(v) && v.length === 0) {
   return true;
 }

 if (typeof v === "string" && v.trim().length === 0) {
   return true;
 }

return false;
}

Solution 22 - Javascript

(null == undefined)  // true

(null === undefined) // false

Because === checks for both the type and value. Type of both are different but value is the same.

Solution 23 - Javascript

Let's look at this,

  1.  

    let apple; // Only declare the variable as apple
    alert(apple); // undefined
    

    In the above, the variable is only declared as apple. In this case, if we call method alert it will display undefined.

  2.  

       let apple = null; /* Declare the variable as apple and initialized but the value is null */
       alert(apple); // null
    

In the second one it displays null, because variable of apple value is null.

So you can check whether a value is undefined or null.

if(apple !== undefined || apple !== null) {
    // Can use variable without any error
}

Solution 24 - Javascript

The foo == null check should do the trick and resolve the "undefined OR null" case in the shortest manner. (Not considering "foo is not declared" case.) But people who are used to have 3 equals (as the best practice) might not accept it. Just look at eqeqeq or triple-equals rules in eslint and tslint...

The explicit approach, when we are checking if a variable is undefined or null separately, should be applied in this case, and my contribution to the topic (27 non-negative answers for now!) is to use void 0 as both short and safe way to perform check for undefined.

Using foo === undefined is not safe because undefined is not a reserved word and can be shadowed (MDN). Using typeof === 'undefined' check is safe, but if we are not going to care about foo-is-undeclared case the following approach can be used:

if (foo === void 0 || foo === null) { ... }

Solution 25 - Javascript

Calling typeof null returns a value of “object”, as the special value null is considered to be an empty object reference. Safari through version 5 and Chrome through version 7 have a quirk where calling typeof on a regular expression returns “function” while all other browsers return “object”.

Solution 26 - Javascript

var x;
if (x === undefined) {
    alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
    alert ("not even declared.")
};

You can only use second one: as it will check for both definition and declaration

Solution 27 - Javascript

var i;

if (i === null || typeof i === 'undefined') {
    console.log(i, 'i is undefined or null')
}
else {
    console.log(i, 'i has some value')
}

Solution 28 - Javascript

I still think the best/safe way to test these two conditions is to cast the value to a string:

var EmpName = $("div#esd-names div#name").attr('class');

// Undefined check
if (Object.prototype.toString.call(EmpName) === '[object Undefined]'){
    // Do something with your code
}

// Nullcheck
if (Object.prototype.toString.call(EmpName) === '[object Null]'){
    // Do something with your code
}

Solution 29 - Javascript

Best way:

if(typeof variable==='undefined' || variable===null) {

/* do your stuff */
}

Solution 30 - Javascript

I know I'm 10 years late. But I'll leave my answer here just in case anybody needs a short method.

Installing Lodash in your project could be useful because of the helper functions that could come in handy in these situations.

Using ES6 modules, import would look like this:

import isNull from 'lodash/isNull';

import isUndefined from 'lodash/isUndefined';

import isNil from 'lodash/isNil';

Would be better if only the used functions are imported.

Lodash's isNull checks if value is null.

const value = null;
 
 if(isNull(value)) {
    // do something if null
 }

lodash's isUndefined checks if value is undefined.

const value = undefined;

if(isUndefined(value)) {
   // do something if undefined.
}

isNil Checks if value is null OR undefined. I prefer this method over the other two because it checks both undefined and null.

Solution 31 - Javascript

You can check if the value is undefined or null by simply using typeof:

if(typeof value == 'undefined'){

Solution 32 - Javascript

Simplest answer: 

if(!EmpName){ DO SOMETHING };

Solution 33 - Javascript

if(x==null) is a bad idea in JavaScript. Judge with "==" - it may cause an unexpected type coercion, and it can't be read by CoffeeScript, never use "==" or "!=" in condition judgment!

if(x) will be better, but be careful with 0 and "". It will be treated as false, not the equal method with "!= null" is true.

Enter image description here

See JavaScript Best Practices.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsadmicrowaveView Question on Stackoverflow
Solution 1 - JavascriptSarfrazView Answer on Stackoverflow
Solution 2 - Javascripttemporary_user_nameView Answer on Stackoverflow
Solution 3 - JavascriptjkindwallView Answer on Stackoverflow
Solution 4 - Javascriptuser216441View Answer on Stackoverflow
Solution 5 - JavascriptThamaraiselvamView Answer on Stackoverflow
Solution 6 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 7 - JavascriptChetan SView Answer on Stackoverflow
Solution 8 - Javascriptphil294View Answer on Stackoverflow
Solution 9 - JavascriptuserPlusView Answer on Stackoverflow
Solution 10 - JavascriptDenisSView Answer on Stackoverflow
Solution 11 - JavascriptHardik DesaiView Answer on Stackoverflow
Solution 12 - JavascriptAngelin NadarView Answer on Stackoverflow
Solution 13 - JavascriptWelshboyView Answer on Stackoverflow
Solution 14 - JavascriptagcView Answer on Stackoverflow
Solution 15 - JavascriptKapilView Answer on Stackoverflow
Solution 16 - JavascriptM. ArnoldView Answer on Stackoverflow
Solution 17 - JavascriptAshan PriyadarshanaView Answer on Stackoverflow
Solution 18 - JavascriptSuhailView Answer on Stackoverflow
Solution 19 - JavascriptDanKodiView Answer on Stackoverflow
Solution 20 - JavascriptTony Tai NguyenView Answer on Stackoverflow
Solution 21 - JavascriptErnestoView Answer on Stackoverflow
Solution 22 - JavascriptFranklin PiousView Answer on Stackoverflow
Solution 23 - JavascriptAnjana KumariView Answer on Stackoverflow
Solution 24 - JavascriptdhiltView Answer on Stackoverflow
Solution 25 - JavascriptJones AgyemangView Answer on Stackoverflow
Solution 26 - JavascriptkeshavView Answer on Stackoverflow
Solution 27 - JavascriptKARTHIKEYAN.AView Answer on Stackoverflow
Solution 28 - Javascriptn1kkouView Answer on Stackoverflow
Solution 29 - JavascriptNishanth MathaView Answer on Stackoverflow
Solution 30 - JavascriptDante_97View Answer on Stackoverflow
Solution 31 - JavascriptgideonView Answer on Stackoverflow
Solution 32 - JavascriptdkburdView Answer on Stackoverflow
Solution 33 - JavascriptAlbert.QingView Answer on Stackoverflow