1046

I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error

alert( x );

How can I catch this error?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Jineesh
  • 11,187
  • 5
  • 24
  • 25
  • 5
    Looks like this is a granddaddy: http://stackoverflow.com/questions/1485840/whether-a-variable-is-undefined http://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or-null - great gramps maybe this: http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript – random Apr 19 '10 at 15:52
  • 3
    [http://stackoverflow.com/questions/519145/how-to-check-whether-a-javascript-variable-defined/519157#519157](http://stackoverflow.com/questions/519145/how-to-check-whether-a-javascript-variable-defined/519157#519157) – jim0thy May 13 '09 at 14:26
  • 1
    This is not a duplicate of the marked duplicate. Variable resolution and object property resolution are very different things. A better duplicate is [*how to check if a variable exist in javascript?*](http://stackoverflow.com/questions/5879319/how-to-check-if-a-variable-exist-in-javascript). – RobG Nov 10 '15 at 02:04
  • Your error is due to the variable not being declared. Most answers are focused on assignment. See [my answer](https://stackoverflow.com/a/48181567/4722345) for more. Additionally many of them incorrectly state that null and undefined are objects in JavaScript. They are [primitives](https://developer.mozilla.org/en-US/docs/Glossary/Primitive), not objects... – JBallin Jan 10 '18 at 06:43

15 Answers15

1852

In JavaScript, null is an object. There's another value for things that don't exist, undefined. The DOM returns null for almost all cases where it fails to find some structure in the document, but in JavaScript itself undefined is the value used.

Second, no, there is not a direct equivalent. If you really want to check for specifically for null, do:

if (yourvar === null) // Does not execute if yourvar is `undefined`

If you want to check if a variable exists, that can only be done with try/catch, since typeof will treat an undeclared variable and a variable declared with the value of undefined as equivalent.

But, to check if a variable is declared and is not undefined:

if (yourvar !== undefined) // Any scope

Previously, it was necessary to use the typeof operator to check for undefined safely, because it was possible to reassign undefined just like a variable. The old way looked like this:

if (typeof yourvar !== 'undefined') // Any scope

The issue of undefined being re-assignable was fixed in ECMAScript 5, which was released in 2009. You can now safely use === and !== to test for undefined without using typeof as undefined has been read-only for some time.

If you want to know if a member exists independent but don't care what its value is:

if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance

If you want to to know whether a variable is truthy:

if (yourvar)

Source

Stephen M Irving
  • 1,324
  • 9
  • 20
Natrium
  • 30,772
  • 17
  • 59
  • 73
  • 75
    undefined is not a reserved word; you (or someone else's code) can do "undefined = 3" and that will break two of your tests. – Jason S May 13 '09 at 14:14
  • 8
    "If you know the variable exists but don't know if there's any value stored in it" -- huh?! – Jason S May 13 '09 at 14:20
  • 38
    I think he is referring to a variable declared that has not been assigned to. eg: var foo; // foo exists but does not have a value – Wally Lawless May 13 '09 at 14:29
  • 5
    Hmmm... I just noticed the "source" link: this entire post is a direct quote from a mailing list, & should probably be edited to make that more clear, as the original author is not available to clarify. – Jason S May 13 '09 at 15:46
  • Also from what I can tell, that section "If you know the variable exists" has no difference from the previous section. The next section ("if you want to know if a member exists independent...") is correct. – Jason S May 13 '09 at 15:48
  • 12
    "In JavaScript null is an object.", that's not actually true, and probably, the culprit of this misconception is the `typeof` operator (`typeof null == 'object'`). The [`null` value](http://es5.github.com/#x4.3.11) is a [primitive value](http://es5.github.com/#primitive_value), which is the only value of the [Null type](http://es5.github.com/#x4.3.12). – Christian C. Salvadó Oct 13 '11 at 07:29
  • For the global scope case, don't you need to ask `window.hasOwnProperty('varname')`? Otherwise, it might be that `varname` already exists, but somebody has set it to `undefined` for the time being. – George Mar 29 '12 at 18:38
  • using `if(!!yourvar)` wouldn't be better? – Michel Ayres Jul 21 '14 at 14:46
  • 1
    Why are some of them backwards and forwards? as in `undefined != yourvar` and` window['varname'] != undefined`? – Robert Mar 10 '15 at 22:03
  • Is it possible to wrap "typeof yourvar != 'undefined'" into a function of some sort? I can't even seem to pass 'yourvar' into a function if it is not declared. – Michelle May 15 '15 at 21:44
  • and optional :: check all variable :: try { some_var.xxx.xxx.xxx x = 't'; }catch(e){ x = 'f'; } console.debug(x); – Ruthe Sep 11 '15 at 07:53
  • @MichelAyres why can't I just do `if (yourvar)` – SuperUberDuper Nov 05 '15 at 10:20
  • what do you mean by ` no constant named undefined.` – SuperUberDuper Nov 05 '15 at 10:23
  • @bobobobo "Netscape did not support the typeof operator until Navigator 3…". `void` was introduced in JScript 2.0 and `typeof` in JScript 1.0. – Knu Jul 08 '16 at 12:28
  • from w3schools - x === undefined to check undefined variables. – Ashok M A Feb 06 '17 at 12:26
  • #1 gotcha in truthiness evaluation (!myVar or == or logic operators) is NaN. NaN does not equal itself. Nor does it loosely evaluate to true or false. If working with something that can return NaN, keep this in mind. Because NaN gets weird. Fortunately it tends to reveal itself (e.g. `NaN && false` returns `NaN`). `isNaN` is the built-in function you want for comparisons. – Erik Reppen Oct 05 '17 at 13:15
  • undefined as a value goes without apices, so x === undefined – LowFieldTheory Apr 03 '18 at 08:32
  • In JavaScript, to have a variable having `undefined` value is identical to have a variable being undeclared. So, the only real way to check if a variable is not existing is to do a try/catch. – Alireza Jul 31 '19 at 19:10
  • 1
    `undefined` was made to no longer be reassignable several years ago. You can safely check if something is equal or not equal to `undefined` without needing to use `typeof` now – Stephen M Irving Mar 25 '20 at 22:23
  • Right answer and Well Explained – Alvaro Castro Sep 29 '20 at 17:02
  • this condition does not work: if (yourvar !== undefined) – Čamo Oct 22 '20 at 08:26
  • 1
    I still use ```typeof aThing === "undefined"``` because if aThing is truly undefined (i.e. it doesn't exist), then you'll produce an Uncaught ReferenceError which is really bad – Timothy Beamish Mar 09 '21 at 22:28
  • Please note that "undefined" and "not defined" are two different things. The OP asks about "not defined" and this "You can now safely use === and !== to test for undefined" is wrong has nothing to do with it. – Alex from Jitbit Nov 12 '21 at 09:35
397

The only way to truly test if a variable is undefined is to do the following. Remember, undefined is an object in JavaScript.

if (typeof someVar === 'undefined') {
  // Your variable is undefined
}

Some of the other solutions in this thread will lead you to believe a variable is undefined even though it has been defined (with a value of NULL or 0, for instance).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael Wales
  • 10,360
  • 8
  • 28
  • 28
  • 20
    Because the question was IS NOT UNDEFINED here should be typeof someVar !== 'undefined', right? – eomeroff Aug 06 '12 at 09:14
  • 1
    Really, I don't think so that undefinded is an object, check documentation first https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures – Nicramus Sep 14 '14 at 15:42
  • 4
    The only test that does not produce a `ReferenceError`. – Nostalg.io Nov 17 '15 at 19:31
  • 2
    This code is correct, but I think saying `undefined` is an object in javascript is misinformation. Does this statement relate to your answer anyway? It is a value `undefined` of type `undefined`, assigned to the global identifier named `undefined`. – SimplGy Aug 15 '16 at 04:34
  • This seems to be a safer answer than the one given by w3schools.com: `(x === undefined)`. As pointed out in [another comment](https://stackoverflow.com/questions/858181/how-to-check-a-not-defined-variable-in-javascript#comment-665913), the value of `undefined` could be redefined and that test would fail. However, using the example given in this answer, that would not be a problem. – Mr. Lance E Sloan Jun 12 '17 at 19:58
  • `undefined` is not an object. `typeof null` is `'object'`, while `typeof undefined` is `'undefined'`. – temporary_user_name Aug 03 '17 at 00:22
  • It's one of the few things in JS that isn't. But `typeof` won't necessarily reveal something isn't an object. Try `6..toString()` in a console to get my meaning. – Erik Reppen Oct 05 '17 at 13:20
  • @ErikReppen What exactly do you mean by `But typeof won't necessarily reveal something isn't an object`? – a better oliver Dec 11 '17 at 14:50
  • without typeof, someVar === undefined should be still fine – LowFieldTheory Apr 03 '18 at 08:34
  • 1
    This is now incorrect in terms of it being the only way. `undefined` has been readonly since ES5. You can safely test for undefined using `if (x === undefined) {...}` or using shorthand like this: `if (x === void 0)`. – Stephen M Irving Mar 25 '20 at 22:40
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined – MindRoasterMir Oct 22 '21 at 13:49
77

Technically, the proper solution is (I believe):

typeof x === "undefined"

You can sometimes get lazy and use

x == null

but that allows both an undefined variable x, and a variable x containing null, to return true.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jason S
  • 184,598
  • 164
  • 608
  • 970
19

An even easier and more shorthand version would be:

if (!x) {
   //Undefined
}

OR

if (typeof x !== "undefined") {
    //Do something since x is defined.
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dmitri Farkov
  • 9,133
  • 1
  • 29
  • 45
  • 29
    the first code-piece can be incorrect if x is being set from a function call. like x = A(); if A doesnt return anything, it will return "undefined" by default. Doing a !x would be true which would be logically correct. However, if A() returns 0 then !x should be false as x=0. However in JS, !0 is also true. – Rajat Dec 30 '09 at 00:49
  • the second code can be shortened to: if(!typeof(XX)){ ... }else{ ... } – Alejandro Silva Jun 06 '14 at 21:53
  • 2
    @AlejandroSilva Sorry for late reply. That won't work since typeof returns a string, so it will return 'undefined' for an undefined variable, which in turn will evaluate as TRUE therefore leading to a false positive of a defined var. – Dmitri Farkov Mar 17 '15 at 20:29
  • 5
    Please get rid of the first snippet, it's just bad – Ruan Mendes Feb 12 '16 at 12:06
  • why not x !== undefined ? – LowFieldTheory Apr 03 '18 at 08:32
  • 2
    Other comments have pointed out that the first example is bad, but not clearly why. So, for any new coders: !x doesn't test whether x is defined, but whether it's truthy. Strings, boolean true, and positive numbers are all truthy (and I might be forgetting some things), but other potentially valid values like 0, boolean false, and an empty string are not truthy. The first example can work for specific use cases (e.g., testing for a string if you can treat empty the same as undefined), but because of the many where it won't, it should not be considered the default way to check. – cfc Nov 14 '18 at 16:50
  • I tried to use if(!x) because it looks so simple... but it doesn't work. The JavaScript stops executing at that point everytime, in all modern browsers. The console shows an error, that x is undefined. Downvoting -1. – Al Kepp Jan 16 '19 at 12:44
  • Both of these examples are now wrong. The first one is wrong because that only tests if x is falsey, not undefined. You will enter the `if` block for more values than just `undefined`, such as `null`, `false,` or even `0`. The second example is just out of date now, though wasn't when you wrote it I suppose. `undefined` was made readonly in ES5 and using `typeof` operator is no longer necessary. – Stephen M Irving Mar 25 '20 at 22:38
  • I don't get why this has so many upvotes. The first method is downright not reliable and fails for some valid values (as pointed out by other comments) and the second one is overly complicated. Two terrible methods for something that should just be `if (x !== undefined)`. – Eric Mar 30 '22 at 13:34
16

I've often done:

function doSomething(variable)
{
    var undef;

    if(variable === undef)
    {
         alert('Hey moron, define this bad boy.');
    }
}
Joe
  • 2,407
  • 18
  • 20
  • 9
    Consider changing "==" to "===". If you call doSomething(null) you will also get the alert. Unless that's what you want. – Jason S May 13 '09 at 15:51
  • Yep. You have to decide if you want equivalent or exactly equal. Either case could have a use. – Joe Jul 07 '11 at 15:41
  • 1
    simplye check like this-> if(typeof variableName !== 'undefined'){ alert(variableName);} – Muhammad Sadiq Aug 19 '15 at 07:56
  • this is useless since you won't be able to pass an undefined var to a function anyway – avalanche1 Feb 12 '17 at 11:42
  • 2
    Sure you can. Try calling a function with no argument. – Joe Feb 12 '17 at 19:09
  • Why would you do this rather than just checking against `undefined` itself, or doing it the old way from before `undefined` was read-only using the `typeof` operator? I also have to disagree strongly that `==` has a use . – Stephen M Irving Mar 25 '20 at 22:56
  • JavaScript has evolved a bit in 11 years. – Joe Apr 16 '20 at 13:09
  • This doesn't work with undeclared variables, at least in 2020. `doSomething(asdf) VM1599:1 Uncaught ReferenceError: asdf is not defined at :1:13` – Mike Battaglia Nov 27 '20 at 19:32
  • Mike, it does not work because you have script mode enabled. Its enabled by default if you are using react or similar frameworks. – Ali Mert Çakar Dec 12 '20 at 11:03
13

Sorry for necromancing, but most of the answers here confuse 'undefined' and 'not defined'

  1. Undefined - a variable is declared but it's value is undefined.

  2. Not defined - a variable is not even declared.

The only safe way to check for both cases is use typeof myVar === 'undefined'

myVar === undefined will only check for case number (1). It will still throw "myVar is not defined" for case number (2) if myVar is not even declared. The OP specifically asks about the "not even defined" case (2).

P.S. I do understand that "case 2" is becoming rare in the modern ES6 world, but some old legacy components still live in the past.

Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149
5

The error is telling you that x doesn’t even exist! It hasn’t been declared, which is different than being assigned a value.

var x; // declaration
x = 2; // assignment

If you declared x, you wouldn’t get an error. You would get an alert that says undefined because x exists/has been declared but hasn’t been assigned a value.

To check if the variable has been declared, you can use typeof, any other method of checking if a variable exists will raise the same error you got initially.

if(typeof x  !==  "undefined") {
    alert(x);
}

This is checking the type of the value stored in x. It will only return undefined when x hasn’t been declared OR if it has been declared and was not yet assigned.

Fka
  • 6,044
  • 5
  • 42
  • 60
JBallin
  • 8,481
  • 4
  • 46
  • 51
  • undefined has been readonly since ES5 (2009 release) and you no longer need the `typeof` operator. – Stephen M Irving Mar 25 '20 at 22:44
  • undefined !== not defined, thank you for this answer. If you go if(variable) and its not defined you stil get an error, not with typeof. – Wolle Apr 08 '21 at 07:47
5

The void operator returns undefined for any argument/expression passed to it. so you can test against the result (actually some minifiers change your code from undefined to void 0 to save a couple of characters)

For example:

void 0
// undefined

if (variable === void 0) {
    // variable is undefined
}
svarog
  • 9,477
  • 4
  • 61
  • 77
  • Ding ding! This is the correct answer. Shame it is all the way at the bottom. Everyone is so hung up on still using `typeof` and thinking `undefined` can be reassigned, which hasn't been possible for about a decade. – Stephen M Irving Mar 25 '20 at 22:49
  • This was also safe before ES5 because back then even if you had reassigned `undefined` ,for God only knows what reason, using `void 0` will always return `undefined` regardless. – Stephen M Irving Mar 26 '20 at 17:56
3

The accepted answer is correct. Just wanted to add one more option. You also can use try ... catch block to handle this situation. A freaky example:

var a;
try {
    a = b + 1;  // throws ReferenceError if b is not defined
} 
catch (e) {
    a = 1;      // apply some default behavior in case of error
}
finally {
    a = a || 0; // normalize the result in any case
}

Be aware of catch block, which is a bit messy, as it creates a block-level scope. And, of course, the example is extremely simplified to answer the asked question, it does not cover best practices in error handling ;).

3

Another potential "solution" is to use the window object. It avoids the reference error problem when in a browser.

if (window.x) {
    alert('x exists and is truthy');
} else {
    alert('x does not exist, or exists and is falsy');
}
ubershmekel
  • 11,864
  • 10
  • 72
  • 89
  • This doesn't solve the original question at all and is totally irrelevant. Poster was not asking how to test if something is truthy or falsey, he asked how to test for `undefined`. This will not do that. – Stephen M Irving Mar 25 '20 at 22:43
  • 1
    Although I agree with Stephen, that this does not actualy anwer the question, it was exactly what I was looking for. Thanks @ubershmekel, idea to add "window" object helped me. +1 – Jarda Oct 07 '20 at 23:38
3

Just do something like below:

function isNotDefined(value) {
  return typeof value === "undefined";
}

and call it like:

isNotDefined(undefined); //return true
isNotDefined('Alireza'); //return false
Alireza
  • 100,211
  • 27
  • 269
  • 172
2

I often use the simplest way:

var variable;
if (variable === undefined){
    console.log('Variable is undefined');
} else {
    console.log('Variable is defined');
}

EDIT:

Without initializing the variable, exception will be thrown "Uncaught ReferenceError: variable is not defined..."

simhumileco
  • 31,877
  • 16
  • 137
  • 115
mokiSRB
  • 1,132
  • 7
  • 16
  • 2
    `Uncaught ReferenceError: variable is not defined` – Muhammad Umer Aug 26 '16 at 15:18
  • @MuhammadUmer, wrong! `variable` is defined by `var variable;`. And this snippet will override `variable` in local scope. It can break logic which expects to access a closure or global variable. I.e: `var variable = 1; function test() { var variable; if (variable === undefined){ console.log('Variable is undefined'); } else { console.log('Variable is defined: ' + variable); } } test(); // Variable is undefined` – Евгений Савичев Aug 11 '17 at 16:50
2

You can also use the ternary conditional-operator:

var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);

//var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);
John
  • 760
  • 5
  • 12
  • What if `var a = false;`? You should check that if `a===undefined` instead – Iter Ator Jul 14 '16 at 15:57
  • 1
    Question: check a not-defined variable..... This is undefined variable: `var x;` doing above will throw an error – Muhammad Umer Aug 26 '16 at 15:21
  • 1
    "If a = false, then it will show "i dont know 'a'"" – That's the problem, the question is to test if it's defined, not whether it's true. If a is defined as false, then a is not undefined. This returns the wrong result in that case. See my comment on https://stackoverflow.com/a/858270/2055492 for more detail on why this approach doesn't work. – cfc Nov 14 '18 at 16:54
  • 1
    not only will `!a` test true for `undefined`, it also tests true for `0` and `null` and `false`. This is very incorrect and should be removed. – Stephen M Irving Mar 25 '20 at 22:42
1

We can check undefined as follows

var x; 

if (x === undefined) {
    alert("x is undefined");
} else {
     alert("x is defined");
}
Arshid KV
  • 9,631
  • 3
  • 35
  • 36
1

I use a small function to verify a variable has been declared, which really cuts down on the amount of clutter in my javascript files. I add a check for the value to make sure that the variable not only exists, but has also been assigned a value. The second condition checks whether the variable has also been instantiated, because if the variable has been defined but not instantiated (see example below), it will still throw an error if you try to reference it's value in your code.

Not instantiated - var my_variable; Instantiated - var my_variable = "";

function varExists(el) { 
  if ( typeof el !== "undefined" && typeof el.val() !== "undefined" ) { 
    return true; 
  } else { 
    return false; 
  } 
}

You can then use a conditional statement to test that the variable has been both defined AND instantiated like this...

if ( varExists(variable_name) ) { // checks that it DOES exist } 

or to test that it hasn't been defined and instantiated use...

if( !varExists(variable_name) ) { // checks that it DOESN'T exist }
MistyDawn
  • 856
  • 8
  • 9
  • 1
    Why not return your predicate right away? `return typeof el !== "undefined" && typeof el.val() !== "undefined"` – skubski Mar 14 '19 at 15:32