Checking if a variable exists in javascript
Asked Answered
A

8

64

I know there are two methods to determine if a variable exists and not null(false, empty) in javascript:

1) if ( typeof variableName !== 'undefined' && variableName )

2) if ( window.variableName )

which one is more preferred and why?

Ascocarp answered 23/5, 2013 at 16:31 Comment(4)
Why window.variableName? If the variable is local, that will turn up undefined even if the variable is defined.Smallminded
Also, being "not null" is orthogonal to whether the value of the variable is false.Smallminded
Coffeescript has its own operator for this problem and the JS code generated from it is quite interesting. #9993120Enugu
The titel contains a different question than the text.Gerena
T
116

A variable is declared if accessing the variable name will not produce a ReferenceError. The expression typeof variableName !== 'undefined' will be false in only one of two cases:

  • the variable is not declared (i.e., there is no var variableName in scope), or
  • the variable is declared and its value is undefined (i.e., the variable's value is not defined)

Otherwise, the comparison evaluates to true.

If you really want to test if a variable is declared or not, you'll need to catch any ReferenceError produced by attempts to reference it:

var barIsDeclared = true; 
try{ bar; }
catch(e) {
    if(e.name == "ReferenceError") {
        barIsDeclared = false;
    }
}

If you merely want to test if a declared variable's value is neither undefined nor null, you can simply test for it:

if (variableName !== undefined && variableName !== null) { ... }

Or equivalently, with a non-strict equality check against null:

if (variableName != null) { ... }

Both your second example and your right-hand expression in the && operation tests if the value is "falsey", i.e., if it coerces to false in a boolean context. Such values include null, false, 0, and the empty string, not all of which you may want to discard.

Theodora answered 23/5, 2013 at 16:35 Comment(6)
What's the difference between "a variable is not declared" and " a variable is undeclared"?Regression
@TomasZubiri There is no difference; I've just now changed "test if a variable is undeclared" to "test if a variable is declared or not". I hope that's more clear.Theodora
Oh I get it, because the other test would return false if the variable was declared but the value was undefined.Regression
Is it really necessary to check the error name ? Just curious that what could be errors other than ReferenceError ?Resinoid
@Resinoid The only one I was thinking of was if bar has an underlying getter that throws an error: Object.defineProperty(window, "bar", { get: function (){ throw "something"; })Theodora
Thanks @apsillers. That makes sense.Resinoid
F
20

It is important to note that 'undefined' is a perfectly valid value for a variable to hold. If you want to check if the variable exists at all,

if (window.variableName)

is a more complete check, since it is verifying that the variable has actually been defined. However, this is only useful if the variable is guaranteed to be an object! In addition, as others have pointed out, this could also return false if the value of variableName is false, 0, '', or null.

That said, that is usually not enough for our everyday purposes, since we often don't want to have an undefined value. As such, you should first check to see that the variable is defined, and then assert that it is not undefined using the typeof operator which, as Adam has pointed out, will not return undefined unless the variable truly is undefined.

if ( variableName  && typeof variableName !== 'undefined' )
Frankfort answered 23/5, 2013 at 16:35 Comment(5)
While undefined might by a valid value for a variable to hold, checking typeof will not return undefined unless the variable truly is undefined.Lucrecialucretia
if (window.variableName) has a major flaw, in that it will return a false negative for anything that has been defined, but is falsy. So any variables that are false, 0, '', null, or others will give the wrong result.Jannjanna
Thanks for the excellent points. It further helped to solidify my own understanding and I've updated my answer to reflect your comments.Frankfort
The window. helped me get rid of an referenceexception here. Thanks.Flitting
if ( variableName && typeof variableName !== 'undefined' ) is reversed...it should be if ( typeof variableName !== 'undefined' && variableName ) . My page was crashing until I flipped these two conditions.Seal
I
15

If you want to check if a variable (say v) has been defined and is not null:

if (typeof v !== 'undefined' && v !== null) {
    // Do some operation  
}

If you want to check for all falsy values such as: undefined, null, '', 0, false:

if (v) {
   // Do some operation
}
Inlaw answered 23/5, 2013 at 17:45 Comment(0)
A
5

I'm writing an answer only because I do not have enough reputations to comment the accepted answer from apsillers. I agree with his answer, but

If you really want to test if a variable is undeclared, you'll need to catch the ReferenceError ...

is not the only way. One can do just:

this.hasOwnProperty("bar")

to check if there is a variable bar declared in the current context. (I'm not sure, but calling the hasOwnProperty could also be more fast/effective than raising an exception) This works only for the current context (not for the whole current scope).

Absorbed answered 13/1, 2017 at 18:19 Comment(2)
Not working with the non-global variables e.g. variables within the function.Mutule
What do you mean by that? (did you read the last sentence of my answer, i.e. context vs. scope ...)Absorbed
G
1
if ( typeof variableName !== 'undefined' && variableName )
//// could throw an error if var doesnt exist at all

if ( window.variableName )
//// could be true if var == 0

////further on it depends on what is stored into that var
// if you expect an object to be stored in that var maybe
if ( !!window.variableName )
//could be the right way

best way => see what works for your case
Gauldin answered 23/5, 2013 at 16:42 Comment(0)
F
0

I found this shorter and much better:

    if(varName !== (undefined || null)) { //do something }
Funiculus answered 3/3, 2017 at 14:21 Comment(1)
This will not work. (undefined || null) evaluates to null. This statement is basically just if (varName !== null).Goofy
K
-1

if (variable) can be used if variable is guaranteed to be an object, or if false, 0, etc. are considered "default" values (hence equivalent to undefined or null).

typeof variable == 'undefined' can be used in cases where a specified null has a distinct meaning to an uninitialised variable or property. This check will not throw and error is variable is not declared.

Kashgar answered 23/5, 2013 at 16:37 Comment(0)
A
-1

You can simply do if(variableName){console.log("Variable exist")}

Adaptive answered 25/4, 2021 at 10:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.