You can check the fact with

if (typeof jsVar == 'undefined') {
  ...
}
Answer from alex.zherdev on Stack Overflow
🌐
Dmitri Pavlutin
dmitripavlutin.com › 7-tips-to-handle-undefined-in-javascript
7 Tips to Handle undefined in JavaScript
March 23, 2023 - The variables are not exposed to an uninitialized state, thus you have no risk of accessing undefined · Moving the variables as close as possible to their usage place increases the code readability · High cohesive chunks of code are easier to refactor and extract into separate functions, if necessary · When accessing a non-existing object property, JavaScript returns undefined.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript | MDN
Note: The strict equality operator (as opposed to the standard equality operator) must be used here, because x == undefined also checks whether x is null, while strict equality doesn't. This is because null is not equivalent to undefined. See Equality comparison and sameness for details. ... One reason to use typeof is that it does not throw an error if the variable has not been declared.
🌐
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 - This approach ensures that you handle cases where a variable has not been assigned a value. The nullish coalescing operator (??) is a useful addition to JavaScript that allows you to provide default values for undefined or null variables.
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.)

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › undefined-in-javascript
Undefined in JavaScript - GeeksforGeeks
March 13, 2024 - Handle optional function parameters. Check if an object property exists before accessing it. Detect uninitialized variables during debugging. Remember, understanding undefined is essential for writing reliable and bug-free JavaScript code! ... Help us improve. Share your suggestions to enhance ...
🌐
Codedamn
codedamn.com › news › javascript
Handling Undefined Variable Errors in JavaScript
March 26, 2023 - Yes, you can use a try...catch block to handle undefined variable errors. However, it's generally better to prevent such errors by properly declaring and initializing variables, using the typeof operator, or using default parameters.
🌐
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]
🌐
Medium
medium.com › javascript-scene › handling-null-and-undefined-in-javascript-1500c65d51ae
Handling null and undefined in JavaScript | by Eric Elliott | JavaScript Scene | Medium
November 12, 2019 - That is usually a bug, in my experience. To avoid that trap, don’t use null in JavaScript. If you want special cases for uninitialized or empty values, state machines are a better bet. See above. There are a couple of features that can help you deal with null or undefined values.
Find elsewhere
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript undefined
JavaScript undefined
October 6, 2023 - In this example, you can initialize the counter variable to zero, like this: let counter = 0; console.log(counter); // 0Code language: JavaScript (javascript) If you access a non-existing property of an object, you’ll get undefined.
🌐
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 - In this article, you will learn the various methods and approaches you can use to know if a variable is undefined in JavaScript.
🌐
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 - When working with undefined, it’s often a good idea to use strict equality (===) checks to avoid unexpected behavior. ... Proper handling of undefined variables is crucial for writing robust, error-free JavaScript code.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-handle-an-undefined-key-in-javascript
How to handle an undefined key in JavaScript ? - GeeksforGeeks
May 31, 2022 - <script> let employee_details = { firstName: "ABC", lastName: "DEF", age: 22, designation: "Technical Content Writer", organizationName: "GeeksforGeeks", address: undefined, }; console.log( `Address of an employee is : ${ employee_details?.address === undefined ? "not defined" : employee_details.address }` ); </script> ... Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
🌐
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
<script> var firstName; var lastName = null; // Try to get non existing DOM element var comment = document.getElementById('comment'); console.log(firstName); // Print: undefined console.log(lastName); // Print: null console.log(comment); // Print: null console.log(typeof firstName); // Print: undefined console.log(typeof lastName); // Print: object console.log(typeof comment); // Print: object console.log(null == undefined) // Print: true console.log(null === undefined) // Print: false /* Since null == undefined is true, the following statements will catch both null and undefined */ if(firstNa
🌐
Index.dev
index.dev › blog › check-undefined-variable-javascript
How to Check if a Variable is Undefined in JavaScript
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); };
🌐
Kotlin Discussions
discuss.kotlinlang.org › javascript
How do you handle undefined on dynamic value - JavaScript - Kotlin Discussions
August 29, 2018 - When programming in javascript the following snippet is very common: var foo = someApi.someFoo() if (foo) foo.bar() When a javascript API can return all kind of values (an object, null or undefined), then this is the shortest way in javascript for checking for an actual object.
🌐
Full Stack Foundations
fullstackfoundations.com › blog › javascript error handling, null, and undefined for beginners
JavaScript Error Handling, null, and undefined for Beginners
March 29, 2024 - You might infer that because myObj does not yet have a someFunction property, it would throw an error. Instead, all object properties that have not been assigned carry a value of undefined. In the example, when we try to invoke this function, we get a TypeError because you cannot "invoke" and undefined value.
🌐
Medium
lakin-mohapatra.medium.com › how-to-handle-undefined-properties-in-an-object-in-javascript-46bcdcfdedbc
How to handle undefined properties in an object using javascript? | by Lakin Mohapatra | Medium
December 22, 2022 - If the property is undefined, you can assign a default value to it. For example: Copy code const obj = { a: 1 }; const b = typeof obj.b !== 'undefined' ? obj.b : 0; console.log(b); // Outputs "0" No matter which method you choose, it is important ...
🌐
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.
🌐
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 - This is the most common and recommended way. Use the strict equality operator ( === ) to compare the variable with the primitive value undefined. let maybeDefined; if (maybeDefined === undefined) { console.log("maybeDefined is undefined"); }