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

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript | MDN
// 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 - But we would replace undefined with void(0) or void 0 as seen below: if(typeof user.hobby === void 0){} if(typeof scores[10] === void 0){} if(typeof name === void 0){} ... if(typeof user.hobby === void(0)){} if(typeof scores[10] === void(0)){} ...
🌐
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.
🌐
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.
🌐
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"); }
Find elsewhere
🌐
Index.dev
index.dev › blog › check-undefined-variable-javascript
How to Check if a Variable is Undefined in JavaScript
January 21, 2025 - TypeScript, a superset of JavaScript, provides static type checking at compile time, which eliminates many runtime errors and ensures robust code. // Advanced type checking patterns type TypePredicate<T> = (value: unknown) => value is T; type Nullable<T> = T | null | undefined; // Custom type guard implementation const createTypeGuard = <T>(check: (value: unknown) => boolean): TypePredicate<T> => (value: unknown): value is T => check(value); // Implementation examples const isNonEmptyString = createTypeGuard<string>( (value): value is string => typeof value === 'string' && value.trim().length > 0 ); const isValidDate = createTypeGuard<Date>( (value): value is Date => value instanceof Date && !isNaN(value.getTime()) );
🌐
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.
🌐
Scaler
scaler.com › topics › check-undefined-in-javascript
Javascript Program To Check If A Variable Is Undefined- Scaler Topics
January 10, 2024 - Inside the check_value() function, we have just returned the type of the variable using the typeof() function in Javascript. The function will return the string for name, the number for both age and weight, and undefined for address because the property of address is not defined in the class.
🌐
W3Schools
w3schools.com › jsref › jsref_undefined.asp
JavaScript undefined Property
if (typeof y === "undefined") { txt = "y is undefined"; } else { txt = "y is defined"; } Try it Yourself » ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected] · ...
🌐
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)....
🌐
Favtutor
favtutor.com › articles › check-variable-undefined-javascript
Check if a Variable is Undefined in JavaScript (with code)
December 28, 2023 - If the parameter is not undefined, we print the statement as “Hello [planetName]”. We first use the undefined parameter and print “Hello World!”. Then we assign the value “Earth” to the planet variable and print “Hello Earth!”. We have obtained the desired result. In JavaScript, It is essential to understand how to check for undefined variables to write robust and clean code.
🌐
Altcademy
altcademy.com › blog › how-to-check-undefined-in-javascript
How to check undefined in JavaScript
August 29, 2023 - Use strict equality operator (===) to check for null or undefined. Loose equality operator (==) can lead to unexpected results due to type coercion. Understanding 'undefined' in JavaScript is like learning to navigate the catalog system of a library.
🌐
Sentry
sentry.io › sentry answers › javascript › how can i check for "undefined" in javascript?
How can I Check for "undefined" in JavaScript? | Sentry
December 15, 2022 - You can use the strict equality operator (===) to check if a value is undefined: ... An interesting thing to note is that undefined is not a reserved word in JavaScript. A reserved word is a keyword that can’t be used as an identifier for ...
🌐
DEV Community
dev.to › benjaminmock › how-to-check-if-a-variable-is-undefined-in-js-3g02
💡 How to check if a variable is undefined in JS - DEV Community
January 22, 2020 - The best option when you don't ... evaluating UnaryExpression. If Type(val) is Reference, then a. If IsUnresolvableReference(val) is true, return "undefined"....
🌐
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.
🌐
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.
🌐
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....
🌐
Syncfusion
syncfusion.com › blogs › post › null-vs-undefined-in-javascript
Null vs. Undefined in JavaScript | Syncfusion Blogs
December 10, 2024 - To check if a variable has any value before proceeding further in a program, you can use the loose equality ==null to check for either null or undefined.For example, in the following program, the function assignVal() checks whether the num is ...
🌐
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.