2647

What is the most appropriate way to test if a variable is undefined in JavaScript?

I've seen several possible ways:

if (window.myVariable)

Or

if (typeof(myVariable) != "undefined")

Or

if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
halfbit
  • 54,462
  • 46
  • 195
  • 426
  • 9
    Do you want to check for *only* `undefined`, or `null` as well? – Nick Craver Jun 06 '10 at 20:26
  • 6
    @Robert - that question has an accepted answer that answers here have proven to be wrong – Daniel Schaffer Aug 02 '10 at 18:09
  • 3
    See: [How to check for undefined in javascript?](http://stackoverflow.com/questions/2985771/how-to-check-for-undefined-in-javascript), and [whether a variable is undefined](http://stackoverflow.com/questions/1485840/whether-a-variable-is-undefined) and [How to handle ‘undefined’ in javascript](http://stackoverflow.com/questions/1984721/how-to-handle-undefined-in-javascript) – Shog9 Aug 03 '10 at 08:47
  • 4
    check this http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript – Amr Badawy Aug 02 '10 at 17:59
  • 2
    Explanation for defined/undefined object properties see this: [http://stackoverflow.com/a/18135509/1823469][1] [1]: http://stackoverflow.com/a/18135509/1823469 – Konstantin Smolyanin Aug 08 '13 at 20:41
  • 3
    That "duplicate" is about object properties, so some of the answers don't apply very well to this question, asking about variables. – DCShannon Feb 25 '16 at 03:35
  • 1
    know about undefined and it's relation with scope https://codepen.io/grumpy/post/undefined-scope-in-javascript – AL-zami Sep 19 '17 at 16:51
  • 1
    myVariable === undefined – Steve Tolba Oct 10 '18 at 07:19
  • 1
    The question is good. This post shows how bad js is specially that it is a primary web development tool. It shows how fragile the web development is in this day and age!!! – NoChance Feb 13 '19 at 07:33
  • What about `myVar ===`[`void(0)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void#Description)? – Gerold Broser Nov 29 '19 at 16:53

16 Answers16

2889

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?
}
reformed
  • 3,922
  • 9
  • 51
  • 77
Anurag
  • 132,806
  • 34
  • 214
  • 257
  • 8
    @Anurag, the third case will throw a `ReferenceError` if `myVariable` is not *declared*... – Christian C. Salvadó Aug 02 '10 at 18:12
  • @CMS - thanks, I somehow imagined `myVariable` was declared somewhere, just without a value. – Anurag Aug 02 '10 at 18:15
  • 5
    @Anurag, you're welcome, since you talk about ES5, maybe is worth mentioning that [`undefined`](http://ecma262-5.com/ELS5_HTML.htm#Section_15.1.1.3) is now described as non-writable, non-configurable and non-enumerable. So, `window.undefined = "omg";` will simply fail silently or throw under strict mode. – Christian C. Salvadó Aug 02 '10 at 18:23
  • I abhor your argument against using `undefined`. (Also, you want triple equal signs for comparision against it.) – Thomas Eding Aug 02 '10 at 18:32
  • 7
    Can "typeof" be redefined? – halfbit Aug 02 '10 at 19:09
  • 5
    typeof is a language statement, it cannot be redefined any more than if/else/while/for/function etc. could be. – MooGoo Aug 02 '10 at 19:31
  • @MooGoo If thats the case, then I'll infer that language statements in general can't be redefined ;) – halfbit Aug 02 '10 at 19:44
  • Would anyone know the minification difference between npup's approach and trinthis's approach of myVar === undefined – halfbit Aug 02 '10 at 19:45
  • If you're worried about minification, you can use a variable instead of a string literal to compare against an object's type: `var UNDEF = "undefined"; if (typeof someVar == UNDEF)...` – Tim Down Aug 02 '10 at 20:18
  • @MakerOfThings7 - My experience is that you can see improvements by declaring your own version of certain variables. Minifyers typically won't touch `this` either, so if it is referenced enough times, it is worth to do `var self = this;` in the scope and the minifyer will shorten it to `a` or something. Same thing with `undefined` - if you use it a couple of times in the scope, you can get the "wasted" chars (and more) back via the minifyer. And as for `undefined`, you are then also sure to get a **really** undefined `undefined`, which I think is great. – npup Aug 02 '10 at 22:36
  • Anurag - Thanks for the update... you have the best answer and I'd +1 you again if possible.. – halfbit Nov 02 '10 at 22:10
  • is it okay to check truth with if(window.myVar) ? – Jonathan dos Santos Apr 18 '12 at 13:33
  • 62
    `undefined` is immutable in _modern browsers_. Setting `window.undefined` does nothing. – Paul S. Nov 22 '12 at 17:06
  • This is the best answer on whole internet except it lacks few things: 1) you could also use `obj.hasOwnProperty('who');` in place of `'who' in obj`. 2) even in browsers where undefined can be redefined doing this will return true: `suppose undefined = omg. ok... so var x; typeof x === undefined;//true typeof x == undefined;//false' i am little unsure about second please confirm. – Muhammad Umer Aug 10 '13 at 12:04
  • Since yours is the accepted answer, I'll ask you what do you think of `myVar == void 0` posted here: http://stackoverflow.com/a/21881750/328397 – halfbit Feb 19 '14 at 14:45
  • @MuhammadUmer—the *in* test only works with the global object, it doesn't work for any other execution context so not a general solution (or even useful most of the time). – RobG Apr 25 '14 at 22:35
  • 2
    Can I ask one thing, why someone want to define a getter that throws an exception every time? Am I missing something? Is it a corner case that someone want to abuse the `defineProperty`? – giannis christofakis Aug 29 '14 at 09:56
  • Can I compare with undefined instead of using typeof()=='undefined'? – andig Jan 20 '15 at 08:13
  • @andig: Yes. Never use `typeof` to check for `undefined`. – Ry- Feb 10 '15 at 00:35
  • According to this jsPerf: http://jsperf.com/in-vs-typeof/4 the typeof operator supersedes the in operator in performance by far (~99% slower in Chrome) – Kurt May 21 '15 at 10:31
  • typeof myVar is really useful. – asifaftab87 Jun 22 '15 at 09:46
  • While undefined is not writeable in ES5, nothing prevents code from redefining `undefined` in a local variable or argument. So use `myVar === undefined` if you know no code above yours in the same function will every declare an `undefined`. Otherwise use `typeof myVar === "undefined"`. – dharcourt Oct 02 '15 at 19:05
  • 1
    In modern browsers, you can override undefined only inside a scope that is not global. – Diego Faria Jan 08 '16 at 15:17
  • @CMS your use case doesn't apply in a function. ``` function test() { // abc was never declared. if (abc) { // ReferenceError: abc is not defined } } test() ``` will not throw – stevemao Jul 24 '16 at 01:00
  • @Anurag might be worth including this also both an undefined and null variables are false when using `!!` operator, e.g. `(!!x)` would be false – Jake Lacey Sep 11 '16 at 19:19
  • `function(x){// how here to identify if x is set or not?}` – serge Sep 19 '18 at 14:47
  • What about `theFu ===`[`void(0)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void#Description)? – Gerold Broser Nov 29 '19 at 16:49
1296

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

Thomas Eding
  • 31,027
  • 10
  • 64
  • 101
  • 54
    It's marginally more likely that `undefined` could be redefined, just because people do use it for such checks. Some people habitually put the constant on the left-hand side when doing such checks: `if (undefined == someVariable)`. It only takes a typo for this to silently redefine `undefined`: `if (undefined = someVariable)`. – Tim Down Aug 02 '10 at 20:16
  • 54
    I never write code that has `undefined` on the LHS. Even if I did, the fact that I use `===` instead of `==` makes the typo extremely unlikely. But the fact that `==` is incorrect is more of a worry. In any case, a bug like that is usually easy to find. Kind of like this bug: `typeof x == "undefned"`. – Thomas Eding Dec 01 '11 at 16:20
  • 1
    `==` is not necessarily incorrect: it would be correct if the intention was to match `null` and `undefined`. However, I do agree that writing code like that is a pretty terrible idea. – Tim Down Dec 01 '11 at 16:44
  • 37
    How could this be upvoted 41 times, it simply doesn't work. If `myVar` is indeed undefined the code will throw an error, and it's easy to test - http://jsfiddle.net/WcM5g/ The proper way is `typeof myVar === 'undefined'`. – laurent Jul 11 '13 at 13:31
  • 38
    @Laurent: A joke right? This assumes the variable was declared in some way or the other, such as by a `var` keyword or a function parameter. I would sell my soul before I (intentionally) wrote code that tried acting on undeclared variables in any which way. Remember, undeclared and undefined are two different concepts in JS. – Thomas Eding Jul 11 '13 at 18:18
  • 4
    @ThomasEding, some libraries define namespaces by first checking if the variable exists and creating it if it doesn't (see for instance http://blog.arc90.com/2008/06/06/an-easy-way-to-implement-namespaces-in-javascript/), and doing something like `if (ns === undefined) ns = {};` would not work. If the variable is already declared then indeed no problem. – laurent Jul 12 '13 at 02:01
  • 1
    @Laurent: Again, that is not the only way to do it: `if (window.ns === undefined) window.ns = {};` But I prefer: `if (!("ns" in window)) window.ns = {};` Though admittedly I normally write this kind of code not for namespaces, but for methods: `if (!Array.prototype.map) Array.prototype.map = ...` (Also a 5 year old JS article is hardly state of the art, though I'm sure there isn't short supply of that exact code sequence.) – Thomas Eding Sep 10 '13 at 05:23
  • 2
    @ThomasEding, I think we're in agreement actually. My initial reaction was just that the code above, *on its own* (i.e. with `myVar` not being declared anywhere previously), would not work. However, if the variable is indeed already declared, and the programmer is really *sure* that it is declared, then your code is absolutely fine. I'm not too worried about "undefined" being set to a different value as any such environment would probably be broken beyond salvation anyway. – laurent Sep 10 '13 at 06:26
  • i clarified your answer based on the back-and-forth with @Laurent so that "casual readers" won't be confused. – drzaus Jan 28 '14 at 20:07
  • 4
    If you're worried about undefined being redefined just do ```myVar === void 0``` – TheZ Sep 25 '14 at 22:12
  • very bad advice. some library could define a global 'undefined' and kill your code. use the 'typeof' method, it's safe. – Spongman Oct 03 '14 at 00:38
  • @ThomasEding Your answer and comments are very practical and useful to the discussion. One thing though - beware of 'i never write...', because your librarys and team members may not be as disciplined! – samspot Jan 21 '15 at 17:18
  • @TimDown if someone accidentally reassigns `undefined`, wouldn't you want the program to bug out so that you'd know there was an error and eventually be able to track it down? – Andy Mar 06 '15 at 22:15
  • @Andy: Definitely, which is one reason not to use `undefined` on the left hand side of a comparison. – Tim Down Mar 07 '15 at 18:21
  • 2
    @TimDown yeah, I certainly hope no one has a strange habit of putting null or undefined on the lhs, in any programming language! – Andy Mar 10 '15 at 03:30
  • 14
    @Andy In C (and C++), it is both common and good practice to reverse operands like that, to avoid typos. `if (NULL = myVar)` fails to compile and is instantly caught, whereas `if (myVar = NULL)` creates a bug that may be difficult to track down depending on what other code is around it. Modern compilers should give you a warning, but many experienced C programmers have already developed the habit of swapping the order. – GrandOpener Feb 15 '16 at 20:15
  • 8
    @GrandOpener: `-Wall -Werror`. QED. Now the code doesn't have to read like something that came out of Voynich manuscript. – Thomas Eding Feb 16 '16 at 20:29
  • @ThomasEding - Boost and other libraries have known warnings; http://www.boost.org/doc/libs/1_61_0/more/getting_started/windows.html#errors-and-warnings. – Dan Nissenbaum May 18 '16 at 04:55
  • 3
    Upvoted for both: elegance and pragmatism. If you really, really, really cannot get a wink of sleep, knowing that `undefined` might not be what it should be, wrap your code with an [IIFE](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) like so: `(function(undefined) { if (isItOrNot === undefined) doSomething(); })();`. – aefxx Jun 21 '16 at 19:07
  • This will only work, if variable was declared before. If variable was not declared before, this throws an warning: ' is not defined at ...' To be save, use >> typeof !== "undefined" << Watch out, undefined is a String here, so encapsulate it in quotes! – suther Mar 10 '17 at 06:35
  • 3
    What is wrong with getting an error on a undeclared variable? In most comileable programming languages you cannot even compile when using a variable without declaring it. So I would assume using this can eliminate a lot of mistakes. If you still want to use some JS-magic, use typeof with comments, why it could be possible, the variable is not even declared. – Matt Sep 13 '18 at 08:47
  • Actually the undefined without quotes worked for me – Steve Tolba Oct 10 '18 at 07:18
  • its not working for me in chrome , `uncaught refrence error` when you never defined myvar but `typedef myvar` works – Mahdi Khalili Jul 10 '19 at 09:17
  • What about `myVar ===`[`void(0)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void#Description)? – Gerold Broser Nov 29 '19 at 16:50
259

2020 Update

One of my reasons for preferring a typeof check (namely, that undefined can be redefined) became irrelevant with the mass adoption of ECMAScript 5. The other, that you can use typeof to check the type of an undeclared variable, was always niche. Therefore, I'd now recommend using a direct comparison in most situations:

myVariable === undefined

Original answer from 2010

Using typeof is my preference. It will work when the variable has never been declared, unlike any comparison with the == or === operators or type coercion using if. (undefined, unlike null, may also be redefined in ECMAScript 3 environments, making it unreliable for comparison, although nearly all common environments now are compliant with ECMAScript 5 or above).

if (typeof someUndeclaredVariable == "undefined") {
    // Works
}

if (someUndeclaredVariable === undefined) { 
    // Throws an error
}
Tim Down
  • 292,637
  • 67
  • 429
  • 506
  • 20
    You might want to check if a particular global variable representing a piece of functionality has already been defined. For example, library code may wish to check that the library has not already previously been included. – Tim Down Aug 02 '10 at 20:20
  • 1
    'xyz' in window or 'xyz' in self are much better – Jamie Pate Jun 28 '13 at 17:44
  • @JamiePate: What about `window.foo = undefined`? `"foo" in window` will return `true`. – Tim Down Jun 28 '13 at 21:20
  • don't do that, use null instead. if you have to you can 'xyz' in window && window.xyz !== undefined – Jamie Pate Jun 29 '13 at 03:26
  • 4
    @JamiePate: Just to be clear, I disagree that `'xyz' in window` is a better answer than `typeof xyz == "undefined"` because it is testing the wrong thing. The `in` operator checks for the existence of a property, regardless of its value, while the question at least appears to be asking how to test if the value of a variable is `undefined`. Perhaps a better example for me to choose would have been `var foo; "foo" in window`; this returns true while `foo` is definitely undefined. – Tim Down Jun 29 '13 at 08:55
  • It really depends on the goal. 'checking for undefined' should almost always be `xyz === undefined` imo. If you want to check if a variable exists in an object `'xyz' in abc` is the way to go. implicit use of globals (aka members of the window object) is not a good way to go. Avoid relying on globals in the first place if at all possible. – Jamie Pate Jul 09 '13 at 19:51
  • 1
    @JamiePate: Why is `xyz === undefined` better than `typeof xyz == "undefined"`? Agreed about globals, but of the two of us only you have been recommending checking properties of `window`. – Tim Down Jul 10 '13 at 08:56
  • 5
    It's redundant in most cases (and less readable). If you know xyz is a declared variable, why go through the extra trouble? Type checking and string comparison are much slower in some browsers, so if you do it a lot in a tight loop you will lose some performance. http://jsperf.com/type-of-undefined-vs-undefined/6 – Jamie Pate Jul 10 '13 at 17:25
  • @JamiePate: Fair enough. There's the old argument against `xyz === undefined` about `undefined` being mutable, but that's gone in ECMAScript 5 and I never found it a particularly persuasive argument anyway. – Tim Down Jul 10 '13 at 21:26
83

You can use typeof, like this:

if (typeof something != "undefined") {
    // ...
}
Jacob Relkin
  • 151,673
  • 29
  • 336
  • 313
  • 8
    Or just `something !== undefined`, assuming you've already done `var undefined`, pre-cautiously. – James Jun 06 '10 at 20:25
  • 3
    Good to see you added the quotes now. However, as mentioned in [my answer](http://stackoverflow.com/questions/2985771/how-to-check-for-undefined-in-javascript/2985784#2985784), note that strict comparison (`!==`) is not necessary in this case, since `typeof` will always return a string. – Mathias Bynens Jun 06 '10 at 20:27
  • 14
    Mathias: using strict or non-strict comparison here is a matter of personal taste. Both will always work, and neither is more correct. It could depend on whether your default position is to always use strict comparison unless specifically requiring type coercion (as recommended by Crockford, for example) or whether you prefer to use non-strict comparison except when strictness is required. – Tim Down Jun 06 '10 at 21:39
  • This is inaccurate. You absolutely don't *need* to use `typeof`. – Thomas Eding Mar 22 '19 at 03:39
  • @ThomasEding you sure? What if you check on a variable that could contain a string with potentially a (valid) value of `"undefined"`? (e.g. `var adjective = "undefined";`) – Kamafeather May 08 '19 at 21:51
  • @Kamafeather Look at the many other answers to see that there are alternatives. Hence you don't need to use typeof. – Thomas Eding May 09 '19 at 15:19
  • 1
    Oh, now I got what you mean; your comment is misleading because was looking like related to the correctness of the code. Yes, one doesn't *need* to use it, since everything is matter of tastes; *if you know what you are doing* you don't even *need* to sanitize user inputs; that doesn't mean that it *shouldn't* be done. In this case, among all the answers, using `typeof` is the safest and less error prone option. More than writing such confusing comment I would have edited the answer to use another term instead of *need*. Like *"You can|should|better|might use `typeof`"* for example :) – Kamafeather May 09 '19 at 15:35
67

Update 2018-07-25

It's been nearly five years since this post was first made, and JavaScript has come a long way. In repeating the tests in the original post, I found no consistent difference between the following test methods:

  • abc === undefined
  • abc === void 0
  • typeof abc == 'undefined'
  • typeof abc === 'undefined'

Even when I modified the tests to prevent Chrome from optimizing them away, the differences were insignificant. As such, I'd now recommend abc === undefined for clarity.

Relevant content from chrome://version:

  • Google Chrome: 67.0.3396.99 (Official Build) (64-bit) (cohort: Stable)
  • Revision: a337fbf3c2ab8ebc6b64b0bfdce73a20e2e2252b-refs/branch-heads/3396@{#790}
  • OS: Windows
  • JavaScript: V8 6.7.288.46
  • User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36

Original post 2013-11-01

In Google Chrome, the following was ever so slightly faster than a typeof test:

if (abc === void 0) {
    // Undefined
}

The difference was negligible. However, this code is more concise, and clearer at a glance to someone who knows what void 0 means. Note, however, that abc must still be declared.

Both typeof and void were significantly faster than comparing directly against undefined. I used the following test format in the Chrome developer console:

var abc;
start = +new Date();
for (var i = 0; i < 10000000; i++) {
    if (TEST) {
        void 1;
    }
}
end = +new Date();
end - start;

The results were as follows:

Test: | abc === undefined      abc === void 0      typeof abc == 'undefined'
------+---------------------------------------------------------------------
x10M  |     13678 ms               9854 ms                 9888 ms
  x1  |    1367.8 ns              985.4 ns                988.8 ns

Note that the first row is in milliseconds, while the second row is in nanoseconds. A difference of 3.4 nanoseconds is nothing. The times were pretty consistent in subsequent tests.

Kamafeather
  • 5,651
  • 10
  • 44
  • 74
Zenexer
  • 16,313
  • 6
  • 62
  • 72
  • Aww, so heartbreaking that this is -1; I spent a good amount of time testing this. Oh well. It's good info, so I'll leave it here. Remember, don't use `===` to test for `undefined`! – Zenexer Dec 19 '13 at 07:12
  • 1
    i assume the -1 was because of 1) and clearer at a glance to someone who knows what void 0 means, since `void 0` sounds more unusual to me, 2) you should [share your perf tests](http://jsperf.com/undefined-comparisons) instead, but mainly 3) your first example (`abc === void 0`) throws an exception if `abc` is undefined. – drzaus Jan 28 '14 at 19:53
  • added your method to my test list and it does check out (not that I doubted you) -- http://jsfiddle.net/drzaus/UVjM4/8/ – drzaus Jan 28 '14 at 20:00
  • I think the best compromise between clarity and speed, given these numbers (which are from a while ago), is the `typeof` test. – Zenexer Feb 18 '14 at 07:48
  • 1
    I find it amazing that the undefined compare is slower than to void 0. I imagine that the running JS version is new enough for undefined to be guaranteed constant. So sad. – Thomas Eding Mar 14 '15 at 02:32
25

If it is undefined, it will not be equal to a string that contains the characters "undefined", as the string is not undefined.

You can check the type of the variable:

if (typeof(something) != "undefined") ...

Sometimes you don't even have to check the type. If the value of the variable can't evaluate to false when it's set (for example if it's a function), then you can just evalue the variable. Example:

if (something) {
  something(param);
}
Guffa
  • 640,220
  • 96
  • 678
  • 956
  • 15
    No need for the parentheses: `typeof` is an operator, not a function. – Tim Down Jun 06 '10 at 20:23
  • 7
    @Tim - It can be used both ways. – Nick Craver Jun 06 '10 at 20:24
  • 1
    @Tim: @Nick is correct. See https://developer.mozilla.org/en/Core_Javascript_1.5_Reference/Operators/Special_Operators/typeof_Operator – Mathias Bynens Jun 06 '10 at 20:30
  • 21
    Yes, I know that it *works* with the parentheses, which is because the parentheses here form the grouping operator that simply evaluates and returns the operand inside. I merely said that they were unnecessary. – Tim Down Jun 06 '10 at 21:21
18
if (typeof foo == 'undefined') {
 // Do something
};

Note that strict comparison (!==) is not necessary in this case, since typeof will always return a string.

Mathias Bynens
  • 130,201
  • 49
  • 208
  • 240
  • 4
    What's with the semi-colon (`};`)? – James Jun 06 '10 at 21:05
  • 2
    @J-P: The semicolon after the closing brace is just an empty statement. – Gumbo Jun 06 '10 at 21:26
  • 3
    @Gumbo, sorry, what I meant to ask was: "What purpose is the semi-colon serving?" – James Jun 06 '10 at 21:51
  • 1
    @J-P That’s just a personal preference. I like to add optional semicolons — the `if` block can be seen/rewritten as one line of code, and then it makes sense to append the semicolon, because that’s how I end pretty much every other statement. `if (typeof foo == 'undefined') { };` Also, this ensures compatibility with some JavaScript minifiers. I’m aware JSLint advises against this, but I just don’t see the point — these semicolons are harmless and if anything, enforce a slightly stricter coding style. – Mathias Bynens Jun 07 '10 at 09:33
  • 8
    I've not encountered a minifier that can't handle `if(){}` without a `;` ... Which minifiers are you referring to? You say that this is how you end every other statement... I guess that's true. But, a block statement `{}` is already a statement in and of its own. Adding a `;` makes it two statements, technically. Syntactically, it's redundant. Even automatic semi-colon insertion won't add a semi-colon there... – James Jun 07 '10 at 12:39
  • 2
    @J-P: I guess I started doing it years ago after reading [the Packer documentation](http://dean.edwards.name/packer/usage/sample.html). Packer expects semicolons after `function() {}` declarations. You’re right though — apparently it’s not required after `if` statements, but somehow I still think it makes sense. – Mathias Bynens Jun 07 '10 at 12:55
17

Some scenarios illustrating the results of the various answers: http://jsfiddle.net/drzaus/UVjM4/

(Note that the use of var for in tests make a difference when in a scoped wrapper)

Code for reference:

(function(undefined) {
    var definedButNotInitialized;
    definedAndInitialized = 3;
    someObject = {
        firstProp: "1"
        , secondProp: false
        // , undefinedProp not defined
    }
    // var notDefined;

    var tests = [
        'definedButNotInitialized in window',
        'definedAndInitialized in window',
        'someObject.firstProp in window',
        'someObject.secondProp in window',
        'someObject.undefinedProp in window',
        'notDefined in window',

        '"definedButNotInitialized" in window',
        '"definedAndInitialized" in window',
        '"someObject.firstProp" in window',
        '"someObject.secondProp" in window',
        '"someObject.undefinedProp" in window',
        '"notDefined" in window',

        'typeof definedButNotInitialized == "undefined"',
        'typeof definedButNotInitialized === typeof undefined',
        'definedButNotInitialized === undefined',
        '! definedButNotInitialized',
        '!! definedButNotInitialized',

        'typeof definedAndInitialized == "undefined"',
        'typeof definedAndInitialized === typeof undefined',
        'definedAndInitialized === undefined',
        '! definedAndInitialized',
        '!! definedAndInitialized',

        'typeof someObject.firstProp == "undefined"',
        'typeof someObject.firstProp === typeof undefined',
        'someObject.firstProp === undefined',
        '! someObject.firstProp',
        '!! someObject.firstProp',

        'typeof someObject.secondProp == "undefined"',
        'typeof someObject.secondProp === typeof undefined',
        'someObject.secondProp === undefined',
        '! someObject.secondProp',
        '!! someObject.secondProp',

        'typeof someObject.undefinedProp == "undefined"',
        'typeof someObject.undefinedProp === typeof undefined',
        'someObject.undefinedProp === undefined',
        '! someObject.undefinedProp',
        '!! someObject.undefinedProp',

        'typeof notDefined == "undefined"',
        'typeof notDefined === typeof undefined',
        'notDefined === undefined',
        '! notDefined',
        '!! notDefined'
    ];

    var output = document.getElementById('results');
    var result = '';
    for(var t in tests) {
        if( !tests.hasOwnProperty(t) ) continue; // bleh

        try {
            result = eval(tests[t]);
        } catch(ex) {
            result = 'Exception--' + ex;
        }
        console.log(tests[t], result);
        output.innerHTML += "\n" + tests[t] + ": " + result;
    }
})();

And results:

definedButNotInitialized in window: true
definedAndInitialized in window: false
someObject.firstProp in window: false
someObject.secondProp in window: false
someObject.undefinedProp in window: true
notDefined in window: Exception--ReferenceError: notDefined is not defined
"definedButNotInitialized" in window: false
"definedAndInitialized" in window: true
"someObject.firstProp" in window: false
"someObject.secondProp" in window: false
"someObject.undefinedProp" in window: false
"notDefined" in window: false
typeof definedButNotInitialized == "undefined": true
typeof definedButNotInitialized === typeof undefined: true
definedButNotInitialized === undefined: true
! definedButNotInitialized: true
!! definedButNotInitialized: false
typeof definedAndInitialized == "undefined": false
typeof definedAndInitialized === typeof undefined: false
definedAndInitialized === undefined: false
! definedAndInitialized: false
!! definedAndInitialized: true
typeof someObject.firstProp == "undefined": false
typeof someObject.firstProp === typeof undefined: false
someObject.firstProp === undefined: false
! someObject.firstProp: false
!! someObject.firstProp: true
typeof someObject.secondProp == "undefined": false
typeof someObject.secondProp === typeof undefined: false
someObject.secondProp === undefined: false
! someObject.secondProp: true
!! someObject.secondProp: false
typeof someObject.undefinedProp == "undefined": true
typeof someObject.undefinedProp === typeof undefined: true
someObject.undefinedProp === undefined: true
! someObject.undefinedProp: true
!! someObject.undefinedProp: false
typeof notDefined == "undefined": true
typeof notDefined === typeof undefined: true
notDefined === undefined: Exception--ReferenceError: notDefined is not defined
! notDefined: Exception--ReferenceError: notDefined is not defined
!! notDefined: Exception--ReferenceError: notDefined is not defined
drzaus
  • 21,536
  • 14
  • 123
  • 183
  • 1
    note the use of `undefined` within a scope wrapper; this not only protects against the (unusual) case of "oh but `undefined` can be redefined`" but also 'helps' with minification. – drzaus Jan 28 '14 at 20:13
16

In this article I read that frameworks like Underscore.js use this function:

function isUndefined(obj){
    return obj === void 0;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Marthijn
  • 3,152
  • 2
  • 28
  • 48
14

Personally, I always use the following:

var x;
if( x === undefined) {
    //Do something here
}
else {
   //Do something else here
}

The window.undefined property is non-writable in all modern browsers (JavaScript 1.8.5 or later). From Mozilla's documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined, I see this: One reason to use typeof() is that it does not throw an error if the variable has not been defined.

I prefer to have the approach of using

x === undefined 

because it fails and blows up in my face rather than silently passing/failing if x has not been declared before. This alerts me that x is not declared. I believe all variables used in JavaScript should be declared.

Hrishi
  • 6,940
  • 5
  • 25
  • 26
  • you can redeclare `undefined` using scope wrappers: `(function($, undefined){ /* undefined is 'abc' in here */ })(jQuery, 'abc');`, which is why ppl complain that it's technically not safe unless you're 100% sure you know where your code is being run. – drzaus Jan 28 '14 at 20:10
  • Great point about wanting undeclared variable to blow up - this does not happen with typeof. – FruitBreak Nov 30 '15 at 14:58
10

The most reliable way I know of checking for undefined is to use void 0.

This is compatible with newer and older browsers, alike, and cannot be overwritten like window.undefined can in some cases.

if( myVar === void 0){
    //yup it's undefined
}
Joseph Gabriel
  • 7,785
  • 3
  • 35
  • 52
6

Since none of the other answers helped me, I suggest doing this. It worked for me in Internet Explorer 8:

if (typeof variable_name.value === 'undefined') {
    // variable_name is undefined
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
anmarti
  • 4,785
  • 10
  • 48
  • 92
4
// x has not been defined before
if (typeof x === 'undefined') { // Evaluates to true without errors.
   // These statements execute.
}

if (x === undefined) { // Throws a ReferenceError

}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
sourcecode
  • 3,210
  • 1
  • 15
  • 12
3

On the contrary of @Thomas Eding answer:

If I forget to declare myVar in my code, then I'll get myVar is not defined.

Let's take a real example:

I've a variable name, but I am not sure if it is declared somewhere or not.

Then @Anurag's answer will help:

var myVariableToCheck = 'myVar';
if (window[myVariableToCheck] === undefined)
    console.log("Not declared or declared, but undefined.");

// Or you can check it directly 
if (window['myVar'] === undefined) 
    console.log("Not declared or declared, but undefined.");
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Vikas
  • 22,508
  • 34
  • 110
  • 159
  • 2
    Getting such a `myVar is not defined` error would be a *good* thing then, especially when you specifically write "If i *forget* to declare" [emphasis mine]. I love it when I get errors before my code runs. If you care to see more of my opinion on your answer, I've made relevant comments under my answer. – Thomas Eding Sep 10 '13 at 05:55
3
    var x;
    if (x === undefined) {
        alert ("I am declared, but not defined.")
    };
    if (typeof y === "undefined") {
        alert ("I am not even declared.")
    };

    /* One more thing to understand: typeof ==='undefined' also checks 
       for if a variable is declared, but no value is assigned. In other 
       words, the variable is declared, but not defined. */

    // Will repeat above logic of x for typeof === 'undefined'
    if (x === undefined) {
        alert ("I am declared, but not defined.")
    };
    /* So typeof === 'undefined' works for both, but x === undefined 
       only works for a variable which is at least declared. */

    /* Say if I try using typeof === undefined (not in quotes) for 
       a variable which is not even declared, we will get run a 
       time error. */

    if (z === undefined) {
        alert ("I am neither declared nor defined.")
    };
    // I got this error for z ReferenceError: z is not defined 
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Gaurav
  • 763
  • 8
  • 10
0

I use it as a function parameter and exclude it on function execution that way I get the "real" undefined. Although it does require you to put your code inside a function. I found this while reading the jQuery source.

undefined = 2;

(function (undefined) {
   console.log(undefined); // prints out undefined
   // and for comparison:
   if (undeclaredvar === undefined) console.log("it works!")
})()

Of course you could just use typeof though. But all my code is usually inside a containing function anyways, so using this method probably saves me a few bytes here and there.

Cristian Sanchez
  • 27,279
  • 10
  • 53
  • 59
  • 3
    It will give ReferenceError if the var undeclaredvar is really undeclared. It this is attribute - then it works, example: `var undeclaredvar = window.someUndeclaredVar; if (undeclaredvar === undefined) console.log("it works!").` Please test you example before posting. – bartosz.r Nov 29 '11 at 22:18