ChatGPT解决这个技术问题 Extra ChatGPT

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

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.

Use the inbuilt Nullish coalescing operator (??) Ref; developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@DennisNolan This question was asked in 2010
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 };

u
user229044

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.


I'm trying to test if event is null in firefox and an error blocks the execution: "event is undefined"
@MichaelFever How does that not work? Copy paste this in your console: const y = undefined; y == null; It should return true
@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.
could be tricky: undefined !== null --> true undefined == null --> true
live example of relevant comparisons. lgtm.
t
temporary_user_name

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.


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.
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.
Yes because you wrote !== instead of !=.
-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? jsfiddle.net/3xnbxfsu
@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
v
vsync

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.


@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.
what about directly checking if(variable===undefined) instead of using typeof?
@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
This is a better solution because as @Rogue pointed out, the variable might not be declared.
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?
k
knocte
if (variable == null) {
    // Do stuff, will only match null or undefined, this won't match false
}

Just in case anybody thinks this is another half-answer, this actually does work. undefined evaluates equal to null.
Failed to me in chrome console... ReferenceError: variable is not defined, so it might work, but not for me...
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)
Just figured out 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.
@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...
T
Thamaraiselvam
if (typeof EmpName != 'undefined' && EmpName) {

will evaluate to true if value is not:

null

undefined

NaN

empty string ("")

0

false


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.
Please provide a reference of this javascript especification
This is the same as if (EmpName). If it's undefined will be falsy already.
If variable is not defined. then if(EmpName) will throw error
@Thamaraiselvam I think Rudy might have meant this var EmpName; if (EmpName). Where the variable is defined but not assigned a value.
K
Kamil Kiełczewski

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)

https://i.stack.imgur.com/nkpj6.png

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

https://i.stack.imgur.com/7MeG6.png


Thank you, great answer! What about expressions like if(var) or if(!var) ?
@IceFire example difference: if(var)/if(!var) will execute code for values true/false. The if(var == null) for those values of var NEVER execute code...
Well, this is trivial, but can one of the matrices above also be used to check what the if expressions yield for different values?
@IceFire in my answer there is link to source of this picutres - there is also if statement "matrix" there
C
Chetan S

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 }

Chrome 17.0.963.78 m gives this error: ReferenceError: EmpName is not defined
@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.
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');
t
turivishal

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.


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
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.
You should change all of your == to === here, then this would be a reasonable function.
A
Artog

The shortest and easiest:

if(!EmpName ){
 // DO SOMETHING
}

this will evaluate true if EmpName is:

null

undefined

NaN

empty

string ("")

0

false


Use case here is that I want to know the difference between undefined and false. I will use the check on null then.
M
Mark Amery

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.


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.
This assumes that the script is running in a browser. That's not a given.
H
Hardik Desai

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 === ''){
}

var is a reserved word, this will throw SyntaxError
@dhilt implemented from var to variable
W
Warren Sergent

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;

This did not work for me. I still got the error: ReferenceError: s is not defined for the first example.
R
Richie Bendall

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';
}

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.
a
agc

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/


P
Peter Mortensen

jQuery check element not null:

var dvElement = $('#dvElement');

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

C
Cody Gray

The easiest way to check is:

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

This will execute the code if the variable has a value of false, which is potentially undesirable.
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.
Sorry, but that's incorrect. Here is a JSfiddle to prove it.
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: ecma-international.org/ecma-262/#sec-toboolean
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.
A
Ashan Priyadarshana

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';

P
Peter Mortensen

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

T
Tony Tai Nguyen

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


This does not answer the question, which is "how do I catch null and undefined?" not "how do I catch every falsey value in JavaScript?"
@Aerovistae, I thought I did with console.log(isDeepEqual(null, null)); and console.log(isDeepEqual(undefined, undefined)); ?
D
DanKodi

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');
    }

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.
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.
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.
Your or statement is backwards. Checking that something is undefined would be the first step, not the second.
E
Ernesto

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;
}

F
Franklin Pious
(null == undefined)  // true

(null === undefined) // false

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


P
Peter Mortensen

Let's look at this,

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

d
dhilt

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

B
Bhavya Koshiya

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
}

J
Jones Agyemang

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


K
Karthikeyan
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


P
Peter Mortensen
var i;

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

What happens if the user enters the word 'undefined' ?
Your question is good, it show condition is true so that we need to change the option normal undefined into typeof condition. @Chuck
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.
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.
P
Peter Mortensen

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
}

can you explain why you believe this is the "best/safe way" to perform the tests?
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.
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.
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.
n
noseratio

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([]);