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
🌐
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 ...
🌐
Tutorial Republic
tutorialrepublic.com › faq › how-to-check-if-an-object-property-is-undefined-in-javascript.php
How to Check If an Object Property is Undefined in JavaScript
You can use the typeof operator in combination with the strict equality operator (===) to check or detect if a JavaScript object property is undefined.
Discussions

How can I check for "undefined" in JavaScript? - Stack Overflow
What is the most appropriate way to test if a variable is undefined in JavaScript? ... See: How to check for undefined in javascript?, and whether a variable is undefined and How to handle ‘undefined’ in javascript More on stackoverflow.com
🌐 stackoverflow.com
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
June 13, 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
🌐
Codedamn
codedamn.com › news › javascript
How to check if value is undefined or null in JavaScript
June 8, 2023 - The easiest way to check if a value is either undefined or null is by using the equality operator (==). The equality operator performs type coercion, which means it converts the operands to the same type before making the comparison.
🌐
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.
🌐
Fireship
fireship.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 ...
Top answer
1 of 16
3235

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
1588

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

🌐
TypeScript
typescriptlang.org › docs › handbook › 2 › narrowing.html
TypeScript: Documentation - Narrowing
JavaScript’s looser equality checks with == and != also get narrowed correctly. If you’re unfamiliar, checking whether something == null actually not only checks whether it is specifically the value null - it also checks whether it’s potentially undefined.
Find elsewhere
🌐
JavaScript in Plain English
javascript.plainenglish.io › beginners-guide-how-to-check-null-and-undefined-in-typescript-c6492a07b609
Beginner’s Guide: How to Check Null and Undefined in TypeScript | by Brandon Evans | JavaScript in Plain English
July 17, 2024 - We then attempt to call the toUpperCase method on these variables, which could potentially cause a runtime error if the variable is null or undefined. To prevent the runtime error, we use the “!” operator to assert that the variable is not null or undefined. However, TypeScript’s type checker still raises an error because it doesn’t know if the variable is null or undefined at runtime.
🌐
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 › Global_Objects › JSON › stringify
JSON.stringify() - JavaScript | MDN
The JSON.stringify() static method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. console.log(JSON.stringify({ x: 5, y: 6 })); // Expected output: '{"x":5,"y":6}' console.log( JSON.stringify([new Number(3), new String("false"), new Boolean(false)]), ); // Expected output: '[3,"false",false]' console.log(JSON.stringify({ x: [10, undefined, function () {}, Symbol("")] })); // Expected output: '{"x":[10,null,null,null]}' console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))); // Expected output: '"2006-01-02T15:04:05.000Z"'
🌐
Medium
medium.com › front-end-weekly › beginners-guide-dealing-with-undefined-in-javascript-d98ac7e413db
Beginner’s Guide: Dealing with Undefined in JavaScript | by Brandon Evans | Frontend Weekly | Medium
June 8, 2023 - In the above example, we use the in operator to check if the obj object has a name property. The operator returns true if the property exists and false otherwise. By using the in operator, you can avoid accessing properties that are not present ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript | MDN
January 10, 2026 - 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!"
🌐
Codedamn
codedamn.com › news › javascript
How to check for undefined in JavaScript?
September 17, 2022 - The simplest way to check for undefined in JavaScript is simply to use an if/else statement and check if the value is equal to undefined using the === operator.
🌐
Site Title
ftp.pink-ribbon.be › home › the ultimate guide to checking if a variable is undefined in javascript
The Ultimate Guide to Checking if a Variable is Undefined in JavaScript
October 18, 2024 - The equality operator (==) is a fundamental tool in JavaScript for comparing the values of two operands. When used to compare a variable to undefined, it returns true if the variable is undefined.
🌐
Scaler
scaler.com › home › topics › javascript program to check if a variable is undefined
Javascript Program To Check If A Variable Is Undefined- Scaler Topics
January 11, 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, ...
🌐
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 typeof operator returns the data type of variable. Use strict equality to compare the result with the string "undefined". This can be useful in cases where you need to handle other data types that might evaluate to false in an if statement (e.g., 0, empty string).
🌐
STechies
stechies.com › check-variable-undefined-null
How to Check if the Variable is undefined or null in Javascript
August 16, 2022 - In JavaScript, users can use the equality operator (==) to check whether a variable is undefined or null. ... Again, if we consider the Strict Equality Operator (===) and check a given variable, it will return "undefined".
🌐
Zig
ziglang.org › documentation › master
Documentation - The Zig Programming Language
undefined can be coerced to any type. Once this happens, it is no longer possible to detect that the value is undefined. undefined means the value could be anything, even something that is nonsense according to the type. Translated into English, undefined means "Not a meaningful value.