🌐
W3Schools
w3schools.com › jsref › jsref_undefined.asp
W3Schools.com
The undefined property indicates that a variable has not been assigned a value, or not declared at all.
🌐
W3Schools
w3schools.com › js › tryit.asp
W3Schools online HTML editor
The W3Schools online code editor allows you to edit code and view the result in your browser
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript | MDN
A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value.
🌐
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').
🌐
W3Schools Blog
w3schools.blog › home › difference between undefined value and null value
Difference between undefined value and null value - W3schools
April 24, 2018 - A value that is not defined and has no keyword is known as an undefined value whereas a null value is explicitly specified by the keyword “null”.
🌐
W3docs
w3docs.com › javascript
The Difference Between Null and Undefined in JavaScript
Undefined is a variable in the global scope. The default value of undefined is the primitive value undefined.
🌐
Dmitri Pavlutin
dmitripavlutin.com › 7-tips-to-handle-undefined-in-javascript
7 Tips to Handle undefined in JavaScript
March 23, 2023 - A detailed article about 'undefined' keyword in JavaScript. 7 tips on how to handle correctly 'undefined' and increase code durability.
🌐
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, ...
Find elsewhere
🌐
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 - Beginner’s Guide: Dealing with Undefined in JavaScript Learn the fundamentals of handling undefined values in JavaScript and avoid common pitfalls. In JavaScript, the undefined value represents the …
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.)

🌐
W3Schools
w3schools.invisionzone.com › browser scripting › javascript
Uncaught ReferenceError: $ is not defined - W3Schools Forum
September 1, 2020 - Hi there, I was following this a tutorial about adding a page fade-in once the page has loaded. It is set up so it works even if javascript is disabled, which is ideal. https://www.abeautifulsite.net/a-clean-fade-in-effect-for-webpages However i am trying to add another class the snippet to the s...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › undefined-in-javascript
Undefined in JavaScript - GeeksforGeeks
March 13, 2024 - Example: In the below example sayhi() function actually outputs and returns nothing. We assigned the sayhi function to the x variable, so we get an Undefined value in the x variable as the sayhi() function returns nothing.
🌐
DEV Community
dev.to › nashmeyah › undefined-vs-null-vs-undeclared-9f8
Undefined vs. Null vs. Undeclared - DEV Community
March 29, 2021 - "The undefined property indicates that a variable has not been assigned a value, or not declared at all.", (W3Schools, Online).
🌐
Flexiple
flexiple.com › javascript › undefined-vs-null-javascript
Undefined vs Null - Javascript - Flexiple
Understand the key differences between undefined and null in JavaScript. Learn how each is used and when to apply them effectively.
Top answer
1 of 2
3

It's not an object; that's just an example of why even today w3schools is a poor resource.

The undefined "value" (it's problematic to call it a value as it's more like the lack of a value) is a marker indicating that something just isn't present. It's somewhat odd that it's distinct from null, but it is.

The way you're testing for undefined is incorrect. You should either compare directly to undefined:

if (something === undefined) 

or compare by type:

if (typeof something === "undefined")

It's very often the case that you don't really care whether something is undefined or null, in which case you can safely do this:

if (something == null)

because undefined is treated as being the same as null in an == comparison. (If you're a believer in the "never use ==" religion, then obviously you wouldn't do that.)

2 of 2
0

In most recent JS implementations, undefined cannot be redefined (you could before). undefined = object will still return undefined. Previously you could redefine undefined however that could cause compatibility issues if another library/script ALSO redefined undefined OR if it expected undefined to really be undefined. It is(was) thus a "really bad idea" to redefine undefined.

To compare against undefined correctly you have to do object === undefined not object == "undefined". "undefined" between the quotes is a String.

There are other ways (typeof object == "undefined") since typeof returns a String; that solution is a bit more obtuse to read and easier to make a mistake in my personal opinion but compatible with older JS implementations.

You can do object = undefined to empty the variable, that's why it's there.

🌐
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 - When this object is used to create URL search parameters, it will interpret the keyword 'undefined' as a string, which hopefully if your favorite http client omits undefined properties for you in requests, you're lucky, but some serialize it incorrectly. I even resort to having a helper function to create query parameters from an object to avoid this · function createUrlSearchParamsFor(payload) { const safePayload = payload ? JSON.parse(JSON.stringify(payload)) : payload return new URLSearchParams(safePayload); }