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 - 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)){} ...
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
What is the best method to check if a variable is not null or empty?
It depends what you mean by empty, or how strict you want to be. These values will coerce to false: undefined null '' (empty string) 0 NaN Everything else coerces to true. So, if you are OK with rejecting all of those values, you can do: if(PostCodeInformation) { } If you want to make sure that PostCodeInformation is really an object value (and not a number or boolean, etc): if(typeof PostCodeInformation === 'object' && PostCodeInformation !== null) { } You have to do the null-check there, because in JavaScript typeof null returns 'object'. So dumb. If you want to make sure that PostCodeInformation has some property that you really need: if(PostCodeInformation && PostCodeInformation.myCoolProperty) { } Etc, etc More on reddit.com
🌐 r/javascript
18
3
August 2, 2015
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
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript | MDN
The undefined global property represents the primitive value undefined. It is one of JavaScript's primitive types. function test(t) { if (t === undefined) { return "Undefined value!"; } return t; } let x; console.log(test(x)); // Expected output: "Undefined value!"
🌐
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.
🌐
Favtutor
favtutor.com › articles › check-variable-undefined-javascript
Check if a Variable is Undefined in JavaScript (with code)
December 28, 2023 - We directly compare the value that the variable holds with the undefined keyword. The “if” condition is true and hence we have obtained the desired result. The typeof operator is used to check the type of any variable.
🌐
W3Schools
w3schools.com › jsref › jsref_undefined.asp
JavaScript undefined Property
let x; if (typeof x === "undefined") { text = "x is undefined"; } else { text = "x is defined"; } Try it Yourself » · More examples below. The undefined property indicates that a variable has not been assigned a value, or not declared at all. ...
🌐
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. ... Checking for `undefined`` this way will work in every use case except for one, if the variable ...
Find elsewhere
🌐
Sentry
sentry.io › sentry answers › javascript › how can i check for "undefined" in javascript?
How can I Check for "undefined" in JavaScript? | Sentry
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 ...
🌐
Index.dev
index.dev › blog › check-undefined-variable-javascript
How to Check if a Variable is Undefined in JavaScript
January 21, 2025 - Here, typeof x returns the string 'undefined' if x is undeclared or its value is undefined, preventing any errors. This combined check ensures that x is both declared and strictly equals 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 - // Declare a variable let myVariable; // Condition to check variable is defined or not if (typeof myVariable === "undefined") { console.log("myVariable is undefined"); } else { console.log("myVariable is defined"); }
🌐
Vultr Docs
docs.vultr.com › javascript › examples › check-if-a-variable-is-undefined-or-null
JavaScript Program to Check If A Variable Is undefined or null | Vultr Docs
November 6, 2024 - The results are true if the comparisons match exactly, illustrating that a is undefined and b is null. Check if a variable is undefined by using the typeof operator.
🌐
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"....
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing
Nullish coalescing operator (??) - JavaScript | MDN
The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. const foo = null ?? "default string"; console.log(foo); // Expected output: "default string" ...
🌐
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.
🌐
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
Note: The undefined is not a reserved ... test undefined variable or property is using the typeof operator, like this: if(typeof myVar === 'undefined')....
🌐
Altcademy
altcademy.com › blog › how-to-check-undefined-in-javascript
How to check undefined in JavaScript
August 29, 2023 - This is the safest way as it does not throw an error even if the variable has not been declared. Use strict equality operator (===) to check for null or undefined. Loose equality operator (==) can lead to unexpected results due to type coercion.
🌐
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.
🌐
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!
🌐
Futurestud.io
futurestud.io › tutorials › check-if-a-value-is-null-or-undefined-in-javascript-or-node-js
Check if a Value Is Null or Undefined in JavaScript or Node.js
August 4, 2022 - The value == null comparison is a handy way to check for null and undefined simultaneously. The loose equality operator attempts to convert and compare operands of different types. I’m the maintainer of the @supercharge/goodies package providing convenient helper functions for Node.js and JavaScript.
🌐
Programiz
programiz.com › javascript › examples › check-undefined-null
JavaScript Program To Check If A Variable Is undefined or null
This is because null == undefined evaluates to true. ... // program to check if a variable is undefined or null function checkVariable(variable) { if( typeof variable === 'undefined' || variable === null ) { console.log('The variable is undefined or null'); } else { console.log('The variable ...