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
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!"
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
🌐
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. ...
🌐
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)){} ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript | MDN
For example, if obj.first is a Falsy value that's not null or undefined, such as 0, it would still short-circuit and make nestedProp become 0, which may not be desirable. With the optional chaining operator (?.), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second: ... By using the ?. operator instead of just ., JavaScript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second.
🌐
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 ...
🌐
Scaler
scaler.com › topics › check-undefined-in-javascript
Javascript Program To Check If A Variable Is Undefined- Scaler Topics
January 10, 2024 - ... In the first step, we have declared 4 variables a, b, c, and d and initialized b with 21, c with 'string', and d with null · Inside the check_value() function, we have applied the if-else statements to check whether the variable is null, ...
Find elsewhere
🌐
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.
🌐
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 ...
🌐
The Valley of Code
thevalleyofcode.com › how-to-check-undefined-property-javascript
How to check if a JavaScript object property is undefined
It is used without parentheses, passing it any value you want to check: const list = [] const count = 2 typeof list //"object" typeof count //"number" typeof "test" //"string" typeof color //"undefined" If the value is not defined, typeof returns the ‘undefined’ string.
🌐
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 ...
🌐
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"); }
🌐
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')....
🌐
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.
🌐
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.
🌐
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" ...
🌐
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.
🌐
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 ...
🌐
2ality
2ality.com › 2013 › 04 › check-undefined
Checking for undefined: === versus typeof versus falsiness
April 19, 2013 - > Boolean(undefined) false Hence, you can check for undefined like this: if (!x) ...