If you are interested in finding out whether a variable has been declared regardless of its value, then using the in operator is the safest way to go. Consider this example:

// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"

But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the in operator for a more robust check.

"theFu" in window; // true
"theFoo" in window; // false

If you are interested in knowing whether the variable hasn't been declared or has the value undefined, then use the typeof operator, which is guaranteed to return a string:

if (typeof myVar !== 'undefined')

Direct comparisons against undefined are troublesome as undefined can be overwritten.

window.undefined = "foo";
"foo" == undefined // true

As @CMS pointed out, this has been patched in ECMAScript 5th ed., and undefined is non-writable.

if (window.myVar) will also include these falsy values, so it's not very robust:

false
0
""
NaN
null
undefined

Thanks to @CMS for pointing out that your third case - if (myVariable) can also throw an error in two cases. The first is when the variable hasn't been defined which throws a ReferenceError.

// abc was never declared.
if (abc) {
    // ReferenceError: abc is not defined
} 

The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,

// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", { 
    get: function() { throw new Error("W00t?"); }, 
    set: undefined 
});
if (myVariable) {
    // Error: W00t?
}
Answer from Anurag on Stack Overflow
Top answer
1 of 16
3234

If you are interested in finding out whether a variable has been declared regardless of its value, then using the in operator is the safest way to go. Consider this example:

// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"

But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the in operator for a more robust check.

"theFu" in window; // true
"theFoo" in window; // false

If you are interested in knowing whether the variable hasn't been declared or has the value undefined, then use the typeof operator, which is guaranteed to return a string:

if (typeof myVar !== 'undefined')

Direct comparisons against undefined are troublesome as undefined can be overwritten.

window.undefined = "foo";
"foo" == undefined // true

As @CMS pointed out, this has been patched in ECMAScript 5th ed., and undefined is non-writable.

if (window.myVar) will also include these falsy values, so it's not very robust:

false
0
""
NaN
null
undefined

Thanks to @CMS for pointing out that your third case - if (myVariable) can also throw an error in two cases. The first is when the variable hasn't been defined which throws a ReferenceError.

// abc was never declared.
if (abc) {
    // ReferenceError: abc is not defined
} 

The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,

// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", { 
    get: function() { throw new Error("W00t?"); }, 
    set: undefined 
});
if (myVariable) {
    // Error: W00t?
}
2 of 16
1586

I personally use

myVar === undefined

Warning: Please note that === is used over == and that myVar has been previously declared (not defined).


I do not like typeof myVar === "undefined". I think it is long winded and unnecessary. (I can get the same done in less code.)

Now some people will keel over in pain when they read this, screaming: "Wait! WAAITTT!!! undefined can be redefined!"

Cool. I know this. Then again, most variables in Javascript can be redefined. Should you never use any built-in identifier that can be redefined?

If you follow this rule, good for you: you aren't a hypocrite.

The thing is, in order to do lots of real work in JS, developers need to rely on redefinable identifiers to be what they are. I don't hear people telling me that I shouldn't use setTimeout because someone can

window.setTimeout = function () {
    alert("Got you now!");
};

Bottom line, the "it can be redefined" argument to not use a raw === undefined is bogus.

(If you are still scared of undefined being redefined, why are you blindly integrating untested library code into your code base? Or even simpler: a linting tool.)


Also, like the typeof approach, this technique can "detect" undeclared variables:

if (window.someVar === undefined) {
    doSomething();
}

But both these techniques leak in their abstraction. I urge you not to use this or even

if (typeof myVar !== "undefined") {
    doSomething();
}

Consider:

var iAmUndefined;

To catch whether or not that variable is declared or not, you may need to resort to the in operator. (In many cases, you can simply read the code O_o).

if ("myVar" in window) {
    doSomething();
}

But wait! There's more! What if some prototype chain magic is happening…? Now even the superior in operator does not suffice. (Okay, I'm done here about this part except to say that for 99% of the time, === undefined (and ****cough**** typeof) works just fine. If you really care, you can read about this subject on its own.)

🌐
freeCodeCamp
freecodecamp.org › news › javascript-check-if-undefined-how-to-test-for-undefined-in-js
JavaScript Check if Undefined – How to Test for Undefined in JS
November 7, 2024 - An undefined variable or anything without a value will always return "undefined" in JavaScript. This is not the same as null, despite the fact that both imply an empty state. You'll typically assign a value to a variable after you declare it, ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript | MDN
js · let x; if (x === undefined) { // these statements execute } else { // these statements do not execute } Note: The strict equality operator (as opposed to the standard equality operator) must be used here, because x == undefined also checks whether x is null, while strict equality doesn't.
🌐
ui.dev
ui.dev › check-for-undefined-javascript
How to check for undefined in JavaScript
The way I recommend to check for undefined in JavaScript is using the strict equality operator, ===, and comparing it to the primitive undefined.
🌐
BrowserStack
browserstack.com › home › guide › how to check if a variable is undefined in javascript
How to Check if a Variable is Undefined in JavaScript | BrowserStack
February 18, 2025 - In JavaScript, undefined is the default value for variables that have been declared but not initialized. On the other hand, null is an intentional assignment that explicitly indicates the absence of a value. ... This article covers different ways to check if a variable is undefined, helping you write code that handles these situations smoothly.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-check-for-undefined-value-in-javascript
How to check for "undefined" value in JavaScript ? - GeeksforGeeks
July 23, 2025 - // Using the 'typeof' operator: // Declare a variable let fruit; // Condition for check variable is defined or not if (typeof fruit === "undefined") { console.log("fruit is undefined"); } else { console.log("fruit is defined"); }
🌐
Tutorial Republic
tutorialrepublic.com › faq › how-to-determine-if-variable-is-undefined-or-null-in-javascript.php
How to Determine If Variable is Undefined or NULL in JavaScript
In simple words you can say a null ... if a variable is undefined or null you can use the equality operator == or strict equality operator === (also called identity operator)....
Find elsewhere
🌐
Index.dev
index.dev › blog › check-undefined-variable-javascript
How to Check if a Variable is Undefined in JavaScript
The strict equality operator (===) in JavaScript checks whether two values are equal without performing type conversion. This means both the value and the type must be identical for the comparison to return true.
🌐
Programiz
programiz.com › javascript › examples › check-undefined-null
JavaScript Program To Check If A Variable Is undefined or null
// program to check if a variable is undefined or null function checkVariable(variable) { if(variable == null) { console.log('The variable is undefined or null'); } else { console.log('The variable is neither undefined nor null'); } } let newVariable; checkVariable(5); checkVariable('hello'); ...
🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › undefined-check
How to Check if a JavaScript Variable is Undefined - Mastering JS
In JavaScript obj.propName === ... obj has a property and that property is strictly equal to undefined, you should use the in operator....
🌐
The Valley of Code
thevalleyofcode.com › how-to-check-undefined-property-javascript
How to check if a JavaScript object property is undefined
In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator.
🌐
Stack Abuse
stackabuse.com › javascript-check-if-variable-is-a-undefined-or-null
JavaScript: Check if Variable is undefined or null
March 29, 2023 - However, due to the typo, somevariable is checked instead, and the result is: ... In a more complex scenario - it might be harder to spot this typo than in this one. We've had a silent failure and might spend time on a false trail. On the other hand, using just the == and === operators here would have alerted us about the non-existing reference variable: let someVariable = 'Hello!' if (somevariable === 'undefined') { console.log('Undefined variable'); } else if (somevariable === 'null') { console.log('Null-value'); } else { console.log(somevariable); }
🌐
W3Schools
w3schools.com › Jsref › jsref_undefined.asp
JavaScript undefined Property
cssText getPropertyPriority() getPropertyValue() item() length parentRule removeProperty() setProperty() JS Conversion ... let x; if (x === undefined) { text = "x is undefined"; } else { text = "x is defined"; } Try it Yourself »
🌐
Medium
medium.com › deno-the-complete-reference › five-ways-to-check-for-undefined-in-javascript-b5568090df77
Five ways to check for undefined in JavaScript | Tech Tonic
March 10, 2024 - The logical AND operator (&&) evaluates to false if the left operand is false or undefined. You can use this in conjunction with a check for another value to ensure both conditions are met. let someValue = "defined"; let maybeDefined; if (someValue ...
🌐
DEV Community
dev.to › kais_blog › how-to-check-for-undefined-in-javascript-typescript-3men
How to Check For Undefined in JavaScript / TypeScript - DEV Community
January 2, 2021 - The correct way to check if something is undefined in JavaScript / TypeScript: Use the typeof operator!
🌐
Reddit
reddit.com › r/javascript › basic js question: when to check for undefined, null, etc
r/javascript on Reddit: Basic JS question: when to check for undefined, null, etc
September 11, 2016 -

So I'm usually more of a server side developer, but lately I've been working with more of the client code at work. I understand what undefined and null are in JavaScript, but I find myself always checking for both of them. In fact, when checking if a String property exists, I end up writing this:

if(value !== undefined && value !== null && value !== '')

I figure there is a better way than this, and it's probably because I'm not 100% clear of when to check for what. So if someone could help fill me in here on the rules of when to check for undefined vs null, that would be great.

Top answer
1 of 5
28

TL;DR: Use value != null. It checks for both null and undefined in one step.

In my mind, there are different levels of checking whether something exists:

0) 'property' in object - Returns true if the property exists at all, even if it's undefined or null.

  1. object.property !== undefined - Returns true if the property exists and is not undefined. Null values still pass.

  2. object.property != null - Return true if the property exists and is not undefined or null. Empty strings and 0's still pass.

  3. !!object.property - Returns true if the property exists and is "truthy", so even 0 and empty strings are considered false.

From my experience, level 2 is usually the sweet spot. Oftentimes, things like empty strings or 0 will be valid values, so level 3 is too strict. On the other hand, levels 0 and 1 are usually too loose (you don't want nulls or undefineds in your program). Notice that level 1 uses strict equality (!==), while level 2 uses loose equality (!=).

2 of 5
16

I would just say

if (value) {
  // do stuff
}

because

'' || false
// false
null || false
// false
undefined || false
//false

Edit:

Based on this statement

I end up writing this: if(value !== undefined && value !== null && value !== '')

I initially assumed that what OP was really looking for was a better way to ask "is there a value?", but...

if someone could help fill me in here on the rules of when to check for undefined vs null, that would be great.

If you're looking to see if something is "truthy":

if (foo.bar) {
  alert(foo.bar)
}

This won't alert if value is '', 0, false, null, or undefined

If you want to make sure something is a String so you can use string methods:

if (typeof foo.bar === 'string') {
  alert(foo.bar.charAt(0))
}

This won't alert unless value is of type 'string'.

So.. "when to check for undefined vs null"? I would just say, whenever you know that you specifically need to check for them. If you know that you want to do something different when a value is null vs when a value is undefined, then you can check for the difference. But if you're just looking for "truthy" then you don't need to.

🌐
TutorialsPoint
tutorialspoint.com › javascript › javascript_undefined_check.htm
JavaScript - Undefined Check
When the variable is undefined, it means the variable is not declared. Users cant use it in the if-else conditional statement like the above method. To check the type of the undeclared variables, we can use the typeof operator. The typeof operator takes the variable as an operand and returns ...
🌐
Reddit
reddit.com › r/programminghorror › it's hard to check for undefined variables in js
r/programminghorror on Reddit: It's hard to check for undefined variables in JS
December 18, 2019 - For that reason I tend to prefer explicit variable === undefined or variable == undefined (when null is possible) everywhere. Continue this thread ... JavaScript never should have been allowed into the realms of real programming languages like C, C++ (C with objects), JAVA (C++ running on a virtual machine) etc etc. ... Yeah we should just run C in web browsers. ... Within 8 months of learning Node.js I became a full stack dev making twice as much as I was then, and I'll never look back.
🌐
Codedamn
codedamn.com › news › javascript
How to check for undefined in JavaScript?
September 17, 2022 - In this case, we can use it to check if the variable type is “undefined”. Please note that when using the typeof keyword, we need to compare it with the string version of the data type, i.e., “undefined”. Let us look at an example to ...