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
🌐
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.
🌐
W3Schools
w3schools.com › Jsref › jsref_undefined.asp
JavaScript undefined Property
The undefined property indicates that a variable has not been assigned a value, or not declared at all. undefined() is an ECMAScript1 (JavaScript 1997) feature.
Discussions

Why is it undefined
None of the functions return anything, so when the console.log() calls try to log the return values from those function calls, they're left with undefined instead. More on reddit.com
🌐 r/learnjavascript
32
34
July 18, 2023
It's hard to check for undefined variables in JS
Checking for undefined in JavaScript isn't actually all that trivial. Are you using if (variable == undefined)? Sorry, but undefined == null returns true. The difference between null and undefined in JavaScript is subtle, but in some edge-cases it could matter. if (variable === undefined), then? Then you are not taking into account that it is actually possible to overwrite the global variable undefined with a different value and suddenly undefined isn't undefined anymore. Why would anyone do something that stupid? Beats me. But someone could do that. So the canonical way of checking for undefined is if (typeof variable == "undefined"). It uses the typeof operator which is a language keyword and thus can't be overwritten and is guaranteed to return one of a very short list of strings. It's a lovely designed language, isn't it? More on reddit.com
🌐 r/programminghorror
81
822
December 18, 2019
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › undefined-in-javascript
Undefined in JavaScript - GeeksforGeeks
March 13, 2024 - Undefined is a type of Data type in JavaScript. It is a primitive value undefined, when a variable is declared and not initialized or not assigned with any value.
🌐
DEV Community
dev.to › sduduzog › null-vs-undefined-what-to-choose-what-to-use-11g
null vs undefined? What to choose? What to use? - DEV Community
August 23, 2023 - With JavaScript you can travel back in time to make a variable not assigned a value. "But black dynamite, assigning null to a variable does the same thing" see that's where you'd be wrong. Here's an analogy for you. We can say null is like loading a webpage and just getting a blank screen, but undefined is a '404 not found' error.
Top answer
1 of 16
3240

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
1589

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

🌐
Medium
medium.com › @bmeurer › sometimes-undefined-is-defined-7701e1c9eff8
Sometimes undefined is defined. There was always some confusion around… | by Benedikt Meurer | Medium
April 4, 2017 - On the syntax level undefined is just an arbitrary identifier — in contrast to null, true and false, which are keywords in JavaScript. That means, when you write undefined in a JavaScript program, you actually refer to a previously bound name.
Find elsewhere
🌐
Musing Mortoray
mortoray.com › home › the many faces of undefined in javascript
The many faces of undefined in JavaScript - Musing Mortoray
June 26, 2024 - This inconsistency is a common source of undefined-value-related defects in code. This also undermines, and confuses, the purpose of undefined. It does not mean a value does not exist, but is rather just an alternate form of null. It’s only by convention that we consider undefined values to be equivalent to missing values. And not all libraries uphold this convention, not even the standard JavaScript library.
🌐
CoreUI
coreui.io › blog › what-is-the-difference-between-null-and-undefined-in-javascript
What is the Difference Between Null and Undefined in JavaScript · CoreUI
February 9, 2025 - Unlike null, undefined means JavaScript cannot find a meaningful value. In contrast, null means a developer has explicitly assigned an empty value. The value null signals the intentional absence of data or object value.
🌐
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 - An undefined variable or anything without a value will always return "undefined" in JavaScript. This is not the same as null, despite the fact that both imply an empty state. You'll typically assign a value to a variable after you declare it, ...
🌐
web.dev
web.dev › learn › javascript › data-types › null-undefined
null and undefined | web.dev
You can also assign the null value ... undefined is a primitive value assigned to variables that have just been declared, or to the resulting value of an operation that doesn't return a meaningful value....
🌐
Reddit
reddit.com › r/learnjavascript › why is it undefined
r/learnjavascript on Reddit: Why is it undefined
July 18, 2023 - Of a function doesn't have a return statement, then it will always return undefined wehn called. addThree and addFive do not contain the keyword return, this they end up returning undefined. ... Inheritance.
🌐
Mimo
mimo.org › glossary › javascript › undefined
JavaScript undefined: Syntax, Usage, and Examples
When you declare a variable without assigning a value, JavaScript sets it to undefined: ... The variable count exists, but no value was stored in it.
🌐
Reddit
reddit.com › r/programminghorror › it's hard to check for undefined variables in js
r/programminghorror on Reddit: It's hard to check for undefined variables in JS
December 18, 2019 - In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the "object" typeof return value. ... Welcome to web development! ... That is one terrible line :D Thanks for chuckle. ... See, Rust solves this problem in a simple and obvious way: undefined/null values can never happen.
🌐
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 ...
🌐
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).
🌐
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 - This article covers different ways ... In JavaScript, the value undefined is a primitive data type and represents a variable that has been declared but not yet assigned a value....
🌐
Sentry
sentry.io › sentry answers › javascript › undefined versus null in javascript
Undefined versus null in JavaScript | Sentry
October 21, 2022 - In contrast, null is a value that represents nothing. Think of null as an empty container and undefined as the absence of a container. A variable will only have the value null when it is explicitly assigned, and will be of type object. const ...
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › javascript fundamentals
Data types
…But we don’t recommend doing that. Normally, one uses null to assign an “empty” or “unknown” value to a variable, while undefined is reserved as a default initial value for unassigned things.
🌐
Greenroots
blog.greenroots.info › javascript-undefined-and-null-lets-talk-about-it-one-last-time
JavaScript undefined and null: Let's talk about it one last time!
November 12, 2020 - undefined value is typically set by the JavaScript engine when a variable is declared but not assigned with any values. null value is typically set by programmers when they want to assign an empty/blank value.