How to check a not-defined variable in JavaScript

JavascriptVariablesUndefined

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

An even easier and more shorthand version would be:

if (!x) {
   //Undefined
}

OR

if (typeof x !== "undefined") {
    //Do something since x is defined.
}

Solution 5 - Javascript

I've often done:

function doSomething(variable)
{
    var undef;
    
    if(variable === undef)
    {
         alert('Hey moron, define this bad boy.');
    }
}

Solution 6 - Javascript

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
}

Solution 7 - Javascript

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.

Solution 8 - Javascript

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');
}

Solution 9 - Javascript

Just do something like below:

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

and call it like:

isNotDefined(undefined); //return true
isNotDefined('Alireza'); //return false

Solution 10 - Javascript

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.

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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

Solution 14 - Javascript

We can check undefined as follows

var x; 

if (x === undefined) {
    alert("x is undefined");
} else {
     alert("x is defined");
}

Solution 15 - Javascript

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 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJineeshView Question on Stackoverflow
Solution 1 - JavascriptNatriumView Answer on Stackoverflow
Solution 2 - JavascriptMichael WalesView Answer on Stackoverflow
Solution 3 - JavascriptJason SView Answer on Stackoverflow
Solution 4 - JavascriptDmitri FarkovView Answer on Stackoverflow
Solution 5 - JavascriptJoeView Answer on Stackoverflow
Solution 6 - JavascriptsvarogView Answer on Stackoverflow
Solution 7 - JavascriptJBallinView Answer on Stackoverflow
Solution 8 - JavascriptubershmekelView Answer on Stackoverflow
Solution 9 - JavascriptAlirezaView Answer on Stackoverflow
Solution 10 - JavascriptAlex from JitbitView Answer on Stackoverflow
Solution 11 - JavascriptmokiSRBView Answer on Stackoverflow
Solution 12 - JavascriptJohnView Answer on Stackoverflow
Solution 13 - JavascriptЕвгений СавичевView Answer on Stackoverflow
Solution 14 - JavascriptArshid KVView Answer on Stackoverflow
Solution 15 - JavascriptMistyDawnView Answer on Stackoverflow