🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript | MDN
You can use undefined and the strict equality and inequality operators to determine whether a variable has a value. In the following code, the variable x is not initialized, and the if statement evaluates to true. js ·
🌐
W3Schools
w3schools.com › jsref › jsref_undefined.asp
JavaScript undefined Property
cssText getPropertyPriority() getPropertyValue() item() length parentRule removeProperty() setProperty() JS Conversion ... let x; if (x === undefined) { text = "x is undefined"; } else { text = "x is defined"; } Try it Yourself » · let x; if (typeof x === "undefined") { text = "x is undefined"; } else { text = "x is defined"; } Try it Yourself » · More examples below.
🌐
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 - The in operator in JavaScript allows you to check if an object has a specific property. It is particularly useful when you want to verify the existence of a property and avoid accessing undefined properties. ... In the above example, we use the in operator to check if the obj object has a name property.
🌐
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.
🌐
Dmitri Pavlutin
dmitripavlutin.com › 7-tips-to-handle-undefined-in-javascript
7 Tips to Handle undefined in JavaScript
March 23, 2023 - One classic example of the unnecessarily extended life of variables is the usage of for cycle inside a function: ... index, item, and length variables are declared at the beginning of the function body. However, they are used only near the end. What's the problem with this approach? Between the declaration at the top and the usage in for statement the variables index and item are uninitialized and exposed to undefined.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › undefined-in-javascript
Undefined in JavaScript - GeeksforGeeks
March 13, 2024 - If a variable was assigned with a function that does not return any value, then the JavaScript assigns an undefined value to that variable. Example: In the below example sayhi() function actually outputs and returns nothing.
🌐
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
So the correct way to test undefined variable or property is using the typeof operator, like this: if(typeof myVar === '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 the example above, the variable x is declared but not assigned any value, so it is considered undefined.
Find elsewhere
🌐
TutorialsTeacher
tutorialsteacher.com › javascript › javascript-null-and-undefined
Difference between null and undefined in JavaScript
For example, consider the following Greet() function that returns a string. function Greet(){ return "Hi"; } let str = Greet();//"Hi"`} </CodeExample> <p>Now, suppose somebody changes the function as below.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript undefined
JavaScript undefined
October 6, 2023 - In this syntax, the nullish coalesing operator (??) returns the defaultValue if the object.propName is undefined or null. Note that the nullish coalescing operator has been available since ECMAScript 2020. let counter = { current: 0 }; const max = counter.max ?? 100;Code language: JavaScript (javascript) When you call a function with a number of parameters, you often pass the same number of arguments. For example:
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
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 › Glossary › Undefined
Undefined - Glossary | MDN
undefined is a primitive value automatically assigned to variables that have just been declared, or to formal arguments for which there are no actual arguments. js · let x; // create a variable but assign it no value console.log(`x's value is ${x}`); // logs "x's value is undefined" Undefined ...
🌐
Codedamn
codedamn.com › news › javascript
Handling Undefined Variable Errors in JavaScript
March 26, 2023 - In this example, globalVar is a global variable that can be accessed both inside and outside of the function myFunction. However, localVar is a local variable that can only be accessed within the function myFunction. Attempting to access localVar outside of the function results in an undefined variable error.
🌐
Sentry
sentry.io › sentry answers › javascript › how can i check for "undefined" in javascript?
How can I Check for "undefined" in JavaScript? | Sentry
A reserved word is a keyword that can’t be used as an identifier for naming things such as variables, properties, or functions. Reserved words include: import, const, and return. You can use undefined as a variable name, as long as the variable is not in the global scope. As can be seen in the example code below, you can make the typeof undefined equal to string:
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › explain-the-difference-between-undefined-and-not-defined-in-javascript
Explain the difference between undefined and not defined in ...
July 23, 2025 - During the thread of execution, the "console.log(a)" will be printed as undefined. In the next line, we have assigned 5 to variable a. In the console, 5 will be printed. At the last line when JavaScript encounters the "console.log(b)" it searches for "b" inside the memory heap of execution context but it is not available, the JS engine will throw the "Reference Error" with a message of "b is not defined".
🌐
Syncfusion
syncfusion.com › blogs › post › null-vs-undefined-in-javascript
Null vs. Undefined in JavaScript | Syncfusion Blogs
December 10, 2024 - To check if a variable has any value before proceeding further in a program, you can use the loose equality ==null to check for either null or undefined.For example, in the following program, the function assignVal() checks whether the num is undefined or null and assigns the value given by the user only if the variable num is not initialized to any value.
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.