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
// x has not been declared before // evaluates to true without errors if (typeof x === "undefined") { // these statements execute } // Throws a ReferenceError if (x === undefined) { } However, there is another alternative. JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context.
🌐
W3Schools
w3schools.com › jsref › jsref_undefined.asp
JavaScript undefined Property
More examples below. 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.
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 - Accessing a property that doesn’t ... example code: ... let myVariable; if (typeof myVariable === "undefined") { console.log("myVariable is undefined"); } else { console.log("myVariable is defined"); } ... Handle optional function ...
🌐
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 includes() to check if the arr array includes the value undefined. It returns true because undefined is present in the array. The void operator in JavaScript allows you to evaluate an expression and always return undefined as the result.
🌐
Dmitri Pavlutin
dmitripavlutin.com › 7-tips-to-handle-undefined-in-javascript
7 Tips to Handle undefined in JavaScript
March 23, 2023 - For example, clone() is a function that clones a plain JavaScript object. The function is expected to return an object: ... However clone() might be invoked with a non-object argument: 15 or null. The function cannot create a clone from these values, so it returns null — the indicator of a missing object. typeof operator makes the distinction between undefined and null:
🌐
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 the example above, the variable x is declared but not assigned any value, so it is considered undefined. Read More: A detailed guide on JavaScript Web Development
🌐
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
Find elsewhere
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript undefined
JavaScript undefined
October 6, 2023 - This feature is called automatic semicolon insertion (ASI) in JavaScript. The add() function will look like the following to the JavaScript compiler: const add = (a,b) => { return; a + b; };Code language: JavaScript (javascript) That’s why you get the undefined as the return result. When you access an array element that is out-of-bounds, you’ll get the undefined value. For example:
🌐
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); };
🌐
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.
🌐
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 - When a variable is declared or initialized but no value is assigned to it, JavaScript automatically displays "undefined". It looks like this: ... Also, when you try accessing values in, for example, an array or object that doesn’t exist, it will throw undefined.
🌐
TutorialsTeacher
tutorialsteacher.com › javascript › javascript-null-and-undefined
Difference between null and undefined in JavaScript
Generally, variables are undefined when you forgot to assign values or change existing code. For example, consider the following Greet() function that returns a string.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Glossary › Undefined
Undefined - Glossary | MDN
let x; // create a variable but assign it no value console.log(`x's value is ${x}`); // logs "x's value is undefined"
🌐
Musing Mortoray
mortoray.com › home › the many faces of undefined in javascript
The many faces of undefined in JavaScript - Musing Mortoray
June 26, 2024 - The comparison to undefined requires that undefined is a symbol in the language. And for consistency of syntax, it is a real value in the language. This is a choice JavaScript made, likely for implementation simplicity, instead of keeping undefined a special symbol.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › javascript tutorial › javascript undefined
JavaScript undefined | How does undefined work in JavaScript?
August 23, 2025 - We are checking first if the x() function value is “undefined” or not with typof · The x() function does not define the array value because it does not receive the number argument. Therefore, if the condition becomes true, an error will occur. x() function output stored in a variable name with output. Output variable reassigns to String “I am reassigned.” · Printing the reassigned value in the last line. JavaScript all declared and not defined variables automatically assigned to undefined value through JavaScript Machine.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
web.dev
web.dev › learn › javascript › data-types › null-undefined
null and undefined | web.dev
This is an error that has carried ... of JavaScript and been left intentionally unaddressed to avoid breaking expected behavior across the web. ... You might define a variable as null with the expectation that it reflects either a value assigned to it at some point in a script or an explicitly absent value. You can also assign the null value to an existing reference to clear a previous value. undefined is a primitive ...
Top answer
1 of 5
16

There are two things you should understand about undefined:

  • the type undefined that can have only one value
  • the variable undefined

To explain:

  • There are so many values of type number (10, 10.01, 1e1). But there can be only one value of type undefined, and that value is stored in the variable undefined.

  • That value has no literal representation either. For example, number values 1, 100, 1e-1 are all literals of type number, but the value stored in the variable undefined has no literal form.

  • undefined is a variable, just a normal variable, that JavaScript declares and assigns it the value of type undefined in the global scope. So you can do all the following...

    typeof undefined;                       // "undefined"
    
    undefined = 100;
    typeof undefined;                       // "number"
    
    undefined = void 0;
    typeof undefined;                       // "undefined"
    
    window.undefined === undefined;         // true
    window.undefined === void 0;            // true
    
  • if you don't want to use the variable undefined, you can generate the value of type undefined by the expression void 0 -- whose sole purpose is to return a value of type undefined.

...can anyone please explain to me why this thing has been inserted into JavaScript...

JavaScript has had a history of bad design - not because of the people who designed it but because no one could foresee that this little scripting capability they were adding to Netscape would one day underpin the business of billion dollar companies.

...we have null value...

Although null can do things undefined does, it is more or less related to objects rather than scalars. Indeed, JavaScript considers null itself an object -- typeof null returns "object".

2 of 5
10

Sorry for answering an older question but the reason you need both undefined and null is simple: in a prototype-based duck-typing language you absolutely must differentiate between "this object does not define a value for X" and "this object says X is nothing/null/empty".

Without this capability there is no way to walk the prototype chain and so inheritance can't work; you must be able to determine that obj.someProp is undefined so you can look at obj.prototype.someProp, and onward up the chain until you find a value. If obj.someProp returned null there would be no way to know if it really was null or just meant "look at my prototype". The only other way around this is to inject some kludgy magic behind the scenes which breaks your ability to fuzz with the prototype chains and do various other bits of JS black magic.

Like much of Javascript, the idea of undefined and null seems wonky and stupid at first, then absolutely brilliant later (then back to wonky and stupid but with a reasonable explanation).

A language like C# will not compile if you access a property that doesn't exist and other dynamic languages often throw exceptions at runtime when you touch a property that doesn't exist, meaning you have to use special constructs to test for them. Plus classes means when an object is instantiated you already know its inheritance chain and all the properties it has - in JS I can modify a prototype 15 steps up the chain and those changes will appear on existing objects.

🌐
Sentry
sentry.io › sentry answers › javascript › how can i check for "undefined" in javascript?
How can I Check for "undefined" in JavaScript? | Sentry
For example, you may want to check if the value returned from a fetch request is defined before trying to access its properties. How do you do this? There are two common ways to check if a value is undefined. 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...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-check-for-undefined-value-in-javascript
How to check for "undefined" value in JavaScript ? - GeeksforGeeks
July 23, 2025 - // Comparing with the 'undefined' ... variable is defined or not if (profile === undefined) { console.log("profile is undefined"); } else { console.log("profile is defined as", profile); } ... Help us improve....