2645

How do I determine if a 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 when I do this, the JavaScript interpreter halts execution.

Dave Mackey
  • 4,306
  • 21
  • 78
  • 136
sadmicrowave
  • 39,964
  • 34
  • 108
  • 180
  • Possible duplicate of [How do you check for an empty string in JavaScript?](https://stackoverflow.com/questions/154059/how-do-you-check-for-an-empty-string-in-javascript) – T.Todua Dec 04 '18 at 09:29
  • Use the inbuilt Nullish coalescing operator (??) Ref; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator – Dennis Nolan Jul 30 '20 at 01:19
  • @DennisNolan This question was asked in 2010 – not my real name Nov 02 '20 at 03:46
  • if(EmpName == 'undefined') will not test if EmpName is undefined, it will test the string "undefined", so get rid of those single quotes: if(EmpName == undefined) // because 'undefined'without the quotes is... undefined or the simpler if(!EmpName){ // DO SOMETHING }; – user7394313 Oct 20 '21 at 00:32

34 Answers34

3501

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.

user229044
  • 232,980
  • 40
  • 330
  • 338
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 9
    I'm trying to test if event is null in firefox and an error blocks the execution: "event is undefined" – Entretoize Sep 06 '18 at 10:32
  • 1
    Can you share the section of code that's erroring? Use a pastebin link. – temporary_user_name Nov 18 '18 at 15:13
  • 5
    @MichaelFever How does that not work? Copy paste this in your console: `const y = undefined; y == null;` It should return `true` – Seraf Mar 18 '19 at 01:19
  • 1
    `const y = undefined; abc == null;` Will return an error... It seems `undefined` is defined as something... – Chris Stryczynski Apr 05 '19 at 09:44
  • 3
    @ChrisStryczynski In example from your comment you declared `y` constant, but you ware comparing `abc` (not `y`). When I tested `y` via `console.log(y == null);` on Chrome and Firefox I got `true` as result. If you got error then maybe you tried to use assignment operator `=` instead of comparison `==` which would make sense to return error since `const` can't be reassigned. – Pshemo Apr 17 '19 at 20:50
  • 2
    I never suggest to use that kind of comparsion even if it covers two values. Keep using (var === null || var === undefined) instead. – Mike Apr 25 '19 at 08:05
  • 6
    could be tricky: `undefined !== null` --> *true* `undefined == null` --> true – d.popov May 14 '19 at 09:13
  • 4
    [live example](https://repl.it/@RyanHaining1/nullequalsundefined) of relevant comparisons. lgtm. – Ryan Haining Aug 08 '19 at 17:17
  • 3
    @ZaytsevDmitry why would you expect a test if a variable is `null` or `undefined` to pass if the variable equals `0`? The question is not about testing for a truthy value, but rather, testing explicitly for `null` or `undefined`. – rodrigo-silveira Sep 20 '19 at 02:14
  • 1
    eslint enforces a rule disallowing this comparison https://eslint.org/docs/rules/no-eq-null – MikeG Feb 19 '20 at 18:46
  • 2
    The above code by @Sarfraz throws **"Uncaught ReferenceError: variable is not defined"** !!! How can such an answer be accepted so widely? Am I the only one in here for whom this simplest of codes doesn't work? – Apostolos Mar 09 '21 at 16:24
  • 1
    Because everyone understands that this is a comparison for some variable that you already have declared. The word `variable` is a stand-in for your _actual_ variable. The code shown is a recipe that you adapt to fit your need. – Mike 'Pomax' Kamermans Aug 08 '21 at 16:23
  • that doesn't work, `let obj = {}; obj.ha === null \\ return false` – shamaseen Jan 06 '22 at 18:51
  • @shamaseen Understand the answer. `obj.ha == null`. – Константин Ван May 29 '23 at 22:56
1364

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.

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
  • 55
    This will cause a ReferenceError and break execution if variable is not defined or referred to at all in the code, using typeof is safer. – Mani Gandham Jun 15 '14 at 09:49
  • 79
    That's more of a stylistic point. If the variable hasn't been declared at *all*, that's really just bad writing on the part of the author. You should know whether your variable has been declared or not, that shouldn't be a question. But *yes*, if for *some reason* that's the case, this should be changed to *window.variable* instead of just *variable*, which will not cause a reference error. Typeof should be avoided. – temporary_user_name Jun 15 '14 at 15:40
  • 4
    You forgot many use cases. What about data you get from somewhere else such as url query params or json data from some API? What about dynamic structure? You should be able to test if `data['token']` is defined? By the way, you mentioned Angular Framework but why would Angular define some `angular.isDefined` function if it was useless? Your answer is a bit super strict and lack of pragmatism. – MaximeBernard Jul 19 '16 at 12:58
  • 4
    You don't need `typeof` to check `data['token']` -- that can be done by `if (data.token != null) { /* use data.token */ }` . It's not different. You are, however, right about Angular. They have some very specialized methods in there, like `isBlankObject` and `hasCustomToString`. Evidently they wanted to cover both the case where the variable was `undefined`/`null` as well as undeclared references. While you're correct about their code, for most people this is not what they are looking for, and I stand by my assertion that if you think you need it, you're probably mistaken. – temporary_user_name Jul 19 '16 at 15:55
  • 6
    Yes because you wrote `!==` instead of `!=`. – temporary_user_name Oct 12 '16 at 15:39
  • imagine i want to check if load_module_1==1 but the load_module_1 can be undefined because depends on loading ajax. How can in check for its value==1 and does not get the undefined error? in a single line of if(!x){return;} – Miguel Oct 29 '16 at 11:30
  • @Miguel: Typically, such "possibly declared variables" are globals, i.e. properties of the `window` object, and the standard solution is to refer to them explicitly as such, e.g. `if (! window.load_module_1) return;`. – Ilmari Karonen Dec 07 '16 at 18:00
  • One entirely legitimate use case is in Microsoft Dynamics CRM, where the execution of custom scripts is triggered through front end (UI) configuration and variables are passed (or not passed) from a string that is again defined in an input box in the front end. – Dom Jan 06 '17 at 11:37
  • 9
    -OP: The statement about those comparisons being "100% equivalent" is SIMPLY WRONG, as you noted in your own EDIT, the second will cause a ReferenceError. As for the assertion: "You should not have any references to undeclared variables in your code." REALLY? Ever heard of Optional Parameters? https://jsfiddle.net/3xnbxfsu/ – Timothy Kanski Jan 09 '17 at 22:04
  • 25
    @TimothyKanski optional parameters may be undefined if they are optionally not provided, but they are most definitely declared variables. They are declared and have a value of `undefined`, as any declared but uninitialized variable would, ie `var someVar;` so your argument doesn't really hold up – chiliNUT Mar 05 '17 at 01:14
  • 5
    @chiliNUT I gave up on arguing with the people who still comment on this. Once a year or so I ask a mod to clean up comments. There have been so, so many people trying to convince me this is wrong. It never ends. – temporary_user_name Mar 05 '17 at 01:17
  • 1
    @Aerovistae word, lol with a language like JS with 8 gazillion people of all coding levels and backgrounds trying to program it I doubt there will be an end to comments supporting bad practice or outright faulty understanding of a concept like an undeclared variable, which would throw a compiler error in other popular statically typed languages but is capable of just being "smoothed over" in a dynamic language like JS – chiliNUT Mar 05 '17 at 01:29
  • 3
    which is just to say, its a common thing for languages with a low cost of entry like javascript and php vs one where you need a more intricate understanding of how a language works before you can really program in it, such as, say, Haskell or Scala – chiliNUT Mar 05 '17 at 01:43
  • You say "You should not have any references to undeclared variables in your code" but you forget you need to parse service calls which might, or might not declare properties. Someone needs to know if someRemoteObjectReceived.randomProperty is not received at all, null, undefined, true, "true", "false", false, 1 or 0 depending of a series of uncontrollable events. – santi Apr 07 '17 at 07:53
  • 3
    And determining that does not require `typeof`. The answers [here](http://stackoverflow.com/questions/43275854/is-there-any-way-to-distinguish-between-an-unset-property-and-a-property-set-to/43275887#43275911) can distinguish between `undefined` and "not received at all," which is certainly impossible with `typeof`. And to distinguish between the other 8 items you listed, only `===` would get the job done. I can't even begin to imagine how you arrived at the conclusion that `typeof` will distinguish between 0 and 1 or true and false but `===` won't. – temporary_user_name Apr 07 '17 at 10:37
  • 1
    @Aerovistae can I use it as - if (variable != null) {} ? will it give the desired result ? – Pankaj Singh Jul 06 '17 at 10:43
  • 3
    That conditional would evaluate to true in all cases where the variable is neither `null` nor `undefined`, so if that's what you want then yes, it will gives the desired result. You could test that out pretty easily btw :) – temporary_user_name Jul 06 '17 at 13:39
  • Can't you just do `if (variable) ` in Javascript? Also, maybe people mean to reference `instanceof` instead of `typeof` -- that is a best practice according to Nicholas Zakas. – Thomas Aug 02 '17 at 17:58
  • 7
    @Thomas `if (variable)` tests truthiness. It would count out `false`, `0`, `NaN`, and an empty string as well as `null` and `undefined`, so it is not the correct answer here. As for `instanceof`, if the questions is "IS THIS VARIABLE NULL OR UNDEFINED?" (perhaps you *want* the value to be `null` or `undefined`...) you cannot ascertain that with `instanceof`, except by checking that the value *isn't* an instance of any other type, which is crazy. So that is also the wrong answer here. – temporary_user_name Aug 02 '17 at 21:01
  • its better to put undefine in single qoutes, 'undefined' because it will make it more understandable.. – Omer May 14 '18 at 12:04
  • That's explained in the comments above. – temporary_user_name Mar 12 '19 at 22:24
  • Unless I missed something obvious, having tried this, exactly as written I received "variable is not defined".and the code halted. – David J Jul 07 '19 at 15:09
  • 3
    Then I can infer that you copied and pasted my code exactly. This implies to me that you did not realize that `variable` was meant to be replaced with the name of your variable. I think it might be for the best for you to read a basic tutorial on JavaScript. – temporary_user_name Jul 07 '19 at 16:16
  • 2
    @temporary_user_name I feel like your statement 'You should not have any references to undeclared variables in your code' symbolizes the toxicity and the issue of SO which is neglecting various use-case in real life situations. `if ( typeof module != 'undefined' && module.exports ) { module.exports = myModule; } else if ( typeof define == 'function' && define.amd ) { define( function () { return myModule; } ); } else { window.myModule= myModule; }` If I'm building a library and wanted to support various browsers, I should just give up because you think it's bad? – Gyuhyeon Lee Sep 26 '19 at 02:41
  • 2
    SO is to provide references to various users with varying skill level and usecases. It's not your soapbox for asserting which practice is good, if everyone should use functional programming rather than OOP, or whatever. Deadpan stating "X should not be done" is harmful for this community. If you had worded it like "Generally, this would be considered bad practice among others" I would've had no issues. – Gyuhyeon Lee Sep 26 '19 at 02:43
  • @GyuhyeonLee separate browsers should be considered an exception as your code has no influence over what a browser decides to inject. In general, no matter what scripting or coding language you use, it is indeed bad practice to reference undefined variables. JS is just very weird to begin with which doesnt help (for fun, you should watch: https://www.youtube.com/watch?v=et8xNAc2ic8) – xorinzor Jun 28 '22 at 19:00
  • _“This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code”_ Yeah, going to disagree with this one. While it's great to aspire to only use variable that exist, that's not always the reality. Being able to check for undefined/null has legitimate uses, and a multi-line solution with try/catch is not a good answer to this question. Sorry, null/undefined are part of the language, and can be reasonably expected in real-world use across all the platforms and libraries that use JS, so a non-cumbersome solution is necessary. – Slipp D. Thompson Dec 30 '22 at 12:03
297

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.

vsync
  • 118,978
  • 58
  • 307
  • 400
jkindwall
  • 3,816
  • 1
  • 17
  • 17
  • 2
    @Aerovistae I recognize that `typeof` is an operator, not a function, so it doesn't need the parentheses, but I appreciate the parentheses nonetheless - simply for reading clarity. – user664833 Sep 04 '14 at 23:28
  • 1
    what about directly checking if(variable===undefined) instead of using typeof? – Frozen Crayon Mar 05 '15 at 13:45
  • 4
    @ArjunU that will cause a ReferenceError if the variable isn't declared. If you don't know whether or not a variable is declared, used the above solution. If you can guarantee that the variable is at least declared, you can use `variable == null` – Rogue Mar 31 '15 at 16:04
  • 3
    This is a better solution because as @Rogue pointed out, the variable might not be declared. – Abdul Sadik Yalcin May 13 '16 at 11:13
  • Correct me if I am wrong, but isn't the first conditional a superset of the second one, and therefore the second conditional is superfluous? – March Ho May 31 '16 at 03:03
  • @MarchHo No. The first conditional can be false, and the second conditional can be true. Consider the case when variable is defined and has the value `null`. – Francis Litterio Jul 19 '16 at 15:00
  • Thanks for using `typeof`. The var == null way does not "catch" both a null and an undefined, so my if/else statement is useless. But when I use `typeof`, my else will get used and I can control the error printout. – Azurespot Aug 09 '19 at 23:26
  • I used just the first part `if( typeof variable === 'undefined' ){}` since adding the null part would throw a ReferenceError – Uriahs Victor Jun 23 '21 at 06:19
193
if (variable == null) {
    // Do stuff, will only match null or undefined, this won't match false
}
knocte
  • 16,941
  • 11
  • 79
  • 125
  • 15
    Just in case anybody thinks this is another half-answer, this actually does work. `undefined` evaluates equal to `null`. – Chuck Apr 15 '10 at 18:37
  • 4
    Failed to me in chrome console... ReferenceError: variable is not defined, so it might work, but not for me... – Eran Medan Mar 14 '12 at 00:46
  • 52
    It only works for declared variables, not variables that may or may not be declared, which is rarely the case. (You need to use typeof + a null check for that case) –  Mar 15 '12 at 00:07
  • 2
    For some reason JSHint doesn't like this. :( – Web_Designer Jun 18 '13 at 20:54
  • 11
    Just [figured out](http://www.jshint.com/docs/#options) you can add this comment: `/*jshint eqnull:true */` to the top of your JS document or function, and JSHint will stop warning you about your uses of `== null`. – Web_Designer Jun 18 '13 at 21:02
  • as user216441 pointed out this is a nogo for undeclared variables http://jsfiddle.net/U2VHs/3/ –  Aug 07 '13 at 13:39
  • 1
    Let's emphasize that this answer takes advantage of the broken nature of `==` and is therefore unwise....it would be better to SPECIFY `if (variable === null || variable === undefined)`....that way someone reading the code knows *exactly* what it's meant to do and when. – temporary_user_name Jan 22 '14 at 02:56
  • 3
    @Aerovistae can you point me to a reference that explicitly states that `==` is broken. The coercive `if(variable == null)` in this answer makes complete sense to me... – Ben Aston Feb 21 '14 at 21:44
  • 2
    The fact that code makes sense to you doesn't make it sensible code. – temporary_user_name Feb 21 '14 at 22:04
  • 1
    This answer is WRONG. An undefined variable produces `ReferenceError`. – user664833 Sep 04 '14 at 23:59
  • @user216441 “It only works for declared variables, not variables that may or may not be declared” So… it doesn't answer the question, which was “How do I determine if variable is **undefined** or null?” _(It answers the question “How do I determine if known-to-be-defined variable is null?”)_ – Slipp D. Thompson Dec 30 '22 at 12:08
105
if (typeof EmpName != 'undefined' && EmpName) {

will evaluate to true if value is not:

  • null

  • undefined

  • NaN

  • empty string ("")

  • 0

  • false

Thamaraiselvam
  • 6,961
  • 8
  • 45
  • 71
  • 16
    I think this is a dangerous technique that has spread like wild fire. Because a lot of the variables that are checked could be boolean or numbers. So if the user does not fully understand the consequences, this is no good. – usefulBee Jan 20 '16 at 21:18
  • Please provide a reference of this javascript especification – villamejia May 20 '16 at 16:30
  • 2
    This is the same as `if (EmpName)`. If it's `undefined` will be falsy already. – Rudy Nov 11 '16 at 15:39
  • 2
    If variable is not defined. then if(EmpName) will throw error – Thamaraiselvam Nov 12 '16 at 03:44
  • 1
    @Thamaraiselvam I think Rudy might have meant this `var EmpName; if (EmpName)`. Where the variable is defined but not assigned a value. – hungerstar Nov 16 '16 at 15:36
  • @Thamaraiselvam As Aerovistae wrote under "Edit again", you shouldn't be using undefined variables, and throwing an error in this case is good because you'll notice the mistake quickly and fix it. – David Knipe Jan 30 '18 at 22:03
  • @DavidKnipe that will ReferenceError and break execution if the variable is not defined or referred to at all in the code, using `typeof` is safer. If its saas then no problem, If its like self hosted application. Fixing a bug is mess. – Thamaraiselvam Feb 01 '18 at 06:14
  • @Thamaraiselvam I think you've misread what I wrote. I agree that leaving out the `typeof` check will cause a ReferenceError if the variable is not declared. The `typeof` check just means that instead of a compile-time error, the expression will simply evaluate to false. This isn't what OP should want - he should want to fix the undeclared variable. So instead of an error which will immediately be found by a developer, you'll get a potentially much more subtle bug which may take some time to debug and may get into production unnoticed. So in this case it's better to let it throw the exception. – David Knipe Feb 01 '18 at 20:53
  • I do believe if(variable === undefined) without the quotes works best for catching any undefined object or primitive before sending it on to other instructions that might crash with it. – Jules Manson Sep 04 '18 at 20:17
55

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

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
34

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 }
Chetan S
  • 23,637
  • 2
  • 63
  • 78
  • 2
    Chrome 17.0.963.78 m gives this error: `ReferenceError: EmpName is not defined` – Eran Medan Mar 14 '12 at 00:47
  • 9
    @EranMedan I know this is late, but it will hopefully help people who come here later. The reason you get an error is because it has not been declared at all. Usually you'd have EmpName(or some other variable) be passed into a function, or the return value of another function and therefore declared(Example: "var x;"). To test if it returned undefined, or null, or blank string, you can use the above solution. – Dave Jun 25 '13 at 13:24
  • I realise this is a cold question, but jQuery will return `undefined` if the attribute doesn't exist on the element (not just just if the selector has no matching elements, as per the answer). For example, an `img` with no `src` would return `undefined` for `$('img').attr('src');` – codinghands Aug 21 '18 at 13:13
28

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.

turivishal
  • 34,368
  • 7
  • 36
  • 59
phil294
  • 10,038
  • 8
  • 65
  • 98
  • 2
    I have run into a little null checking problem. I want to check if a parameter being passed is null, or an empty object `{ }`. This is a common and silly language problem, but I had forgotten about it. All my searches show answers for undefined of null value, or loose equality comparisons ( == ), but not strict equality ( === ) or equivalent. And then here in your -1 ranked answer at the **very bottom** of the page (before I upvoted) is the answer that eluded me. `Object.keys( obj ).length < 1` or maybe === 0, assuming it will never be -1. Anyways, upvoted to 0, woo. :p –  May 22 '16 at 15:40
  • Thanks, I've been able to drop this function in and clean up a lot of code. Why this isn't a standard JS function is beyond me. – Andy Jun 04 '17 at 17:25
  • 4
    You should change *all* of your ```==``` to ```===``` here, then this would be a reasonable function. – Ben McIntyre Jun 06 '17 at 23:48
23

The shortest and easiest:

if(!EmpName ){
 // DO SOMETHING
}

this will evaluate true if EmpName is:

  • null
  • undefined
  • NaN
  • empty
  • string ("")
  • 0
  • false
Artog
  • 1,132
  • 1
  • 13
  • 25
userPlus
  • 319
  • 3
  • 9
  • 3
    Use case here is that I want to know the difference between undefined and false. I will use the check on null then. – gast128 Sep 16 '19 at 14:39
15

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.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
DenisS
  • 1,637
  • 19
  • 15
  • 3
    Readers should note that an approach like this is idiomatic for checking - from JavaScript running in a browser - whether a *global* variable has been declared, and especially whether a browser-provided global (like the history API) is available. It *will not work* for checking whether a non-global variable is `null` or `undefined`, nor will it work if your JavaScript is running outside a browser (i.e. in Node.js). It will also treat globals set to `0`, `false` or `''` the same as those which are undeclared or `undefined` or `null`, which is usually fine. – Mark Amery Feb 05 '15 at 20:33
  • This assumes that the script is running in a browser. That's not a given. – GreenAsJade Oct 11 '16 at 11:10
13

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 === ''){
}
Hardik Desai
  • 1,089
  • 12
  • 20
10

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';
}
Richie Bendall
  • 7,738
  • 4
  • 38
  • 58
Welshboy
  • 318
  • 4
  • 10
  • 3
    it would be better to set var A = document.getElementById("enterJob") if(A)A.className+= ' current'; this way you do 50% work for same result... But maybe you just did it for shows and then I salute. – Harry Svensson Nov 18 '13 at 22:40
10

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;
Warren Sergent
  • 2,542
  • 4
  • 36
  • 42
Angelin Nadar
  • 8,944
  • 10
  • 43
  • 53
  • This did not work for me. I still got the error: `ReferenceError: s is not defined` for the first example. – Mark May 19 '16 at 22:14
10

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/

agc
  • 173
  • 1
  • 16
7

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';
Ashan Priyadarshana
  • 3,119
  • 3
  • 29
  • 34
5

jQuery check element not null:

var dvElement = $('#dvElement');

if (dvElement.length  > 0) {
    // Do something
}
else{
    // Else do something else
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kapil
  • 191
  • 2
  • 5
4

The easiest way to check is:

if(!variable) {
  // If the variable is null or undefined then execution of code will enter here.
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
M. Arnold
  • 387
  • 3
  • 9
  • 1
    This will execute the code if the variable has a value of `false`, which is potentially undesirable. – byxor Jun 29 '19 at 16:23
  • The question is clear "How to determine if variable is 'undefined' or 'null'?" and in javascript if a variable has a value of null or undefined,its value is false. – M. Arnold Jul 01 '19 at 06:14
  • 2
    Sorry, but that's incorrect. Here is a [JSfiddle](https://jsfiddle.net/w5ynkav3/) to prove it. – byxor Jul 01 '19 at 13:09
  • By your answer, `undefined`, `null` **and** a few other things like empty string, +0, -0 `NaN` and `false` get through. `!` operator coerces the operand- here `variable`- to Boolean: https://www.ecma-international.org/ecma-262/#sec-toboolean – Alireza Jul 31 '19 at 19:02
  • But check the question: "How to determine if a variable is undefined or null", the ! operand used with an if will always return to true if the variable is null or undefined. – M. Arnold Aug 01 '19 at 06:36
4

No one seems to have to posted this yet, so here we go:

a?.valueOf() === undefined works reliably for either null or undefined.

The following works pretty much like a == null or a == undefined, but it could be more attractive for purists who don't like ==

function check(a) {
  const value = a?.valueOf(); 
  if (value === undefined) {
    console.log("a is null or undefined");
  }
  else {
    console.log(value);
  }
}

check(null);
check(undefined);
check(0);
check("");
check({});
check([]);

On a side note, a?.constructor works too:

function check(a) {
  if (a?.constructor === undefined) {
    console.log("a is null or undefined");
  }
}

check(null);
check(undefined);
check(0);
check("");
check({});
check([]);

Updated: we worked out a better way with a fellow StackOverflow member.

I'd personally do:

if (Object.is(a ?? null, null)) {
  // a is null or undefined
}
noseratio
  • 59,932
  • 34
  • 208
  • 486
  • _“`a?.valueOf() === undefined` works reliably”_…. Uh, `a = {valueOf() {}}`. – Константин Ван May 29 '23 at 23:15
  • Yeah you should have also mentioned `a = Object.create(null)`, which could be a less silly but equally useless thing. It isn't a bug a human could introduce by mistake, it has to be done on purpose. Otherwise, yes, it's JavaScript and you can hack it however you want. – noseratio May 30 '23 at 00:29
3

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Suhail
  • 371
  • 2
  • 10
3

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
Tony Tai Nguyen
  • 1,502
  • 13
  • 27
3

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;
}
Ernesto
  • 3,944
  • 1
  • 14
  • 29
2

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');
    }
DanKodi
  • 3,550
  • 27
  • 26
  • Close but no. Lose the `typeof` and compare to `undefined` straight out, not as a string. This works but the extra operator has no effect but to make it wordier. – temporary_user_name Apr 04 '16 at 16:09
  • In this case yes you are right we don't need to use typeof. But it's a good practice to use typeof when you are dealing with undefined variables. One reason to use typeof is that it does not throw an error if the variable has not been declared. – DanKodi Apr 05 '16 at 02:29
  • That's actually a bad thing. You don't want undeclared variables in your code. You want that to throw a ReferenceError so you can find the variable and declare it. Certainly you wouldn't try that in a compiled language like C++! Just because JS allows it doesn't mean it should be done. – temporary_user_name Apr 05 '16 at 04:21
  • 1
    Your or statement is backwards. Checking that something is undefined would be the first step, not the second. – Anthony Rutledge May 21 '16 at 15:32
2
(null == undefined)  // true

(null === undefined) // false

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

Franklin Pious
  • 3,670
  • 3
  • 26
  • 30
2

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
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

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) { ... }
dhilt
  • 18,707
  • 8
  • 70
  • 85
1

You can do something like this, I think its more efficient for multiple value check on the same variable in one condition

const x = undefined;
const y = null;
const z = 'test';

if ([undefined, null].includes(x)) {
  // Will return true
}

if ([undefined, null].includes(y)) {
  // Will return true
}

if ([undefined, null].includes(z)) {
  // Will return false
}
Bhavya Koshiya
  • 1,262
  • 2
  • 8
  • 22
1

You can do (value ?? null) === null as well if you’d like to stick with the === operator and clarify the code.


So, three ways, so far.

  • value == null
  • value === null || value === undefined
  • (value ?? null) === null

I usually avoid ==, but this time, I’d prefer == null.

0

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”.

Jones Agyemang
  • 1,230
  • 16
  • 15
0
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

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
keshav
  • 734
  • 6
  • 19
0
var i;

if (i === null || typeof i === 'undefined') {
    console.log(i, 'i is undefined or null')
}
else {
    console.log(i, 'i has some value')
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
  • 3
    What happens if the user enters the word 'undefined' ? – Chuck Dec 07 '16 at 13:03
  • Your question is good, it show condition is true so that we need to change the option normal undefined into typeof condition. @Chuck – KARTHIKEYAN.A Dec 07 '16 at 13:58
  • This is wrong. `typeof` will never yield `undefined`, only the string `'undefined'`. Moreover, `i == null` is already true if `i` is `undefined`, so the second boolean would be redundant even if it worked. – temporary_user_name Sep 17 '17 at 21:19
  • 2
    This solution (with the conditions reversed) was already provided by @jkindwall on Oct 11, 2013. stackoverflow.com/a/19323555/2943403 This code-only post is completely useless because it adds no new value to the page. In fact, it is adding page bloat and wasting researchers time reading it. Please remove this answer. – mickmackusa May 24 '18 at 00:40
0

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
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
n1kkou
  • 3,096
  • 2
  • 21
  • 32
  • can you explain why you believe this is the "best/safe way" to perform the tests? – sadmicrowave May 31 '17 at 12:50
  • Because the conversion is always returning a "standardized" string (i.e. [object Undefined]), so you don't get into trouble by testing falsy values. That's just my opinion based on experiences I had with truthy/falsy values. – n1kkou May 31 '17 at 13:04
  • Thanks for the explanation. I'm not criticizing, its an interesting answer, I just wanted you to provide some explanation for others as to why this is potentially superior to other methods. – sadmicrowave May 31 '17 at 13:06
  • No worries! I had a lot of issues with this type of comparisons, and until now, I find it as the most useful approach for this matter. – n1kkou May 31 '17 at 13:10
-2

Best way:

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

/* do your stuff */
}
Nishanth Matha
  • 5,993
  • 2
  • 19
  • 28
  • 7
    This exact solution was already provided by @jkindwall on Oct 11, 2013. https://stackoverflow.com/a/19323555/2943403 This code-only post is completely useless because it adds no new value to the page. In fact, it is adding page bloat and wasting researchers time reading it. Please remove this answer. – mickmackusa May 24 '18 at 00:38
-4

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

if(typeof value == 'undefined'){
gideon
  • 23
  • 2
  • See comments in the previous answer (https://stackoverflow.com/a/21273362/6305294) regarding typeof. – Alex Jul 26 '17 at 02:42
  • 4
    This is incorrect. Does not catch `null`. I do not understand why new, incorrect answers are being provided to a question that was given a correct and complete answer many years ago. Do you feel the current answers are somehow insufficient? – temporary_user_name Aug 30 '17 at 15:43
-13

Simplest answer:

if(!EmpName){
  // DO SOMETHING
};
Mr.Turtle
  • 2,950
  • 6
  • 28
  • 46
dkburd
  • 1
  • 4
  • This way, you target also falsy values such as `0` or `''`, whereas we want to target only `nullish`/`undefined` values – Tzahi Leh Oct 07 '21 at 15:40