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

🌐
Scaler
scaler.com › topics › check-undefined-in-javascript
Javascript Program To Check If A Variable Is Undefined- Scaler Topics
January 10, 2024 - In this method to check undefined in javascript, we will use the equality operator whether the variable is null or undefined, or neither of them.
Discussions

Good way to check for variable being not null and not undefined.
There are some style guides that basically say you always should use ===, but you can use == in order to check for null or undefined at the same time. So you could do the following: if (value != null) { // This will run if `value` is not `null` and not `undefined`. } More on reddit.com
🌐 r/javascript
56
32
October 20, 2016
Basic JS question: when to check for undefined, null, etc

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

More on reddit.com
🌐 r/javascript
15
17
September 11, 2016
Should I say boolean === true/false in an if statement?

Depends on the context.

Generally, using truthiness (like in the second block) is idiomatic. You don't need to be defensive about undefined variables if you never expect to work with them.

But, if the null/undefined/etc. case is expected and should be handled differently, then the first block is the idiomatic way of checking for exactly false. These cases are rare, however, and a code block where a certain variable might or might not be defined smells bad.

If you're worried about a case where undefined might arise accidentally (e.g., spelling a variable name incorrectly), consider using a tool like JSHint, which will reliably catch such cases without requiring you to change your style.

More on reddit.com
🌐 r/javascript
60
50
January 20, 2013
Why do I get "Object is possibly 'undefined'"?
I don't know, but my hunch is that since you're passing a function to find, TS won't know if that function will be executed immediately and synchronously, and therefore f potentially may have changed into something falsy before that function gets executed. Interesting case though! More on reddit.com
🌐 r/typescript
45
44
November 14, 2020
🌐
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.
🌐
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.
🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › undefined-check
How to Check if a JavaScript Variable is Undefined - Mastering JS
February 25, 2021 - In JavaScript obj.propName === ... obj has a property and that property is strictly equal to undefined, you should use the in operator....
🌐
SheCodes
shecodes.io › athena › 81408-what-does-undefined-mean-in-javascript
[JavaScript] - What does !==undefined mean in JavaScript? - | SheCodes
Learn about the !==undefined comparison operator in JavaScript and how it is used to check if a variable is not undefined.
🌐
Index.dev
index.dev › blog › check-undefined-variable-javascript
How to Check if a Variable is Undefined in JavaScript
January 21, 2025 - 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. // Optimized undefined checking with edge case handling const isUndefined = (value) => { if (value === undefined) return true; if (typeof value === 'undefined') return true; if (value && typeof value === 'object') { return Object.prototype.toString.call(value) === '[object Undefined]'; } return false; }; // Property existence checking const hasProperty = (obj, prop) => { if (!obj || typeof obj !== 'object') return false; return Object.prototype.hasOwnProperty.call(obj, prop); };
Find elsewhere
🌐
Codereadability
codereadability.com › how-to-check-for-undefined-in-javascript
How to check for undefined in JavaScript
September 21, 2015 - When a variable is declared without being assigned a value its initial value is undefined. How do you check if a value is undefined in JavaScript? The short answer In modern browsers you can safely compare the variable directly to undefined: if (name === undefined) {...} Some people argue against ...
🌐
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!
🌐
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"); }
🌐
Altcademy
altcademy.com › blog › how-to-check-undefined-in-javascript
How to check undefined in JavaScript
August 29, 2023 - Let JavaScript engine do it for you when you do not assign a value to a variable. Use typeof to check if a variable is undefined. This is the safest way as it does not throw an error even if the variable has not been declared.
🌐
Zipy
zipy.ai › blog › how-can-i-check-for-undefined-in-javascript
how can i check for undefined in javascript
April 12, 2024 - Useconst andlet: Modern JavaScript (ES6 and beyond) introduces const and let for block-scoped variable declarations, reducing the scope in which undefined can be an issue. Linting Tools: Employ linting tools like ESLint to catch potential undefined issues during development. Debug and fix code errors with Zipy Error Monitoring. ... Even with meticulous checks for undefined and other best practices, errors can slip through the cracks.
🌐
W3Schools
w3schools.com › jsref › jsref_undefined.asp
JavaScript undefined Property
The undefined property indicates that a variable has not been assigned a value, or not declared at all. undefined() is an ECMAScript1 (JavaScript 1997) feature.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript | MDN
July 8, 2025 - // x has not been declared before // evaluates to true without errors if (typeof x === "undefined") { // these statements execute } // Throws a ReferenceError if (x === undefined) { } However, there is another alternative. JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context. The global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object, using the in operator, for instance:
🌐
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 - Here is what the check will look ... === "undefined"){} if(typeof name === "undefined"){} The void operator is often used to obtain the undefined primitive value....
🌐
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 - In this short guide, we've taken a look at how to check if a variable is null, undefined or nil in JavaScript, using the ==, === and typeof operators, noting the pros and cons of each approach.
🌐
Codedamn
codedamn.com › news › javascript
How to check if value is undefined or null in JavaScript
June 8, 2023 - In this blog post, we have explored various ways to check if a value is undefined or null in JavaScript, as well as gained a deeper understanding of these often misunderstood concepts. By using the methods discussed in this post, you can confidently handle undefined and null values in your JavaScript code.
🌐
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)....
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript | MDN
The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.