Javascript IsDefined Function

posted April 16th 2004 at 1002 EDT in All, Javascript

I recently needed a way to check if a variable was defined in javascript. This function is exactly analogous to the ColdFusion function IsDefined.

<script language="javascript">
// JavaScript Document
/*
// ///////////////////////////
// isdefined v1.0
// 
// Check if a javascript variable has been defined.
// 
// Author : Jehiah Czebotar
// Website: http://www.jehiah.com
// Usage  : alert(isdefined('myvar'));
// ///////////////////////////
*/
function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}
</script>

29 Responses

  1. #1 Louis Lambert
    3 years, 5 months ago

    Should be able to specify the object.
    I use this:

    function isdefined(object, variable)
    {
    return (typeof(eval(object)[variable]) == “undefined”)? false: true;
    }

  2. #2 anyguy
    2 years, 11 months ago

    a bit shorter:

    function isdefined(object, variable)
    {
    return (typeof(eval(object)[variable]) != ‘undefined’);
    }

  3. #3 Dave
    2 years, 8 months ago

    I found this works best. The double negation forces the Javascript to evalueate the return value as true or false. If it isn’t defined, the null value is converted to false. Any other value will return true.

    function isDefined(variable)
    {
    return (!(!(document.getElementById(variable))))
    }

  4. #4 fred
    2 years, 6 months ago

    the method of Dave doesn’t work for javascript variables:
    myVar=’HELLO’;
    alert(isDefined(myVar));

    => The method of anyguy is better.

  5. #5 Dan
    2 years, 3 months ago

    None of these worked for me in Firefox 1.5 on Linux. Although I could check the type of undefined variables on the spot, any time I tried to pass an undefined variable to a function, JavaScript would throw an error and die. It’s possible to work around this by instead passing a string containing the name of the variable, and having the function return an eval of the code instead. Here’s my variation of the original poster’s function:

    function isDefined(variable)
    {
    return eval(’(typeof(’+variable+’) != “undefined”);’);
    }

    Obviously this only works on global variables, and evals should never be called on user input. It’s probably better to just check the type on the spot.

  6. #6 Marton
    2 years, 2 months ago

    Hey guys, you don’t even need such a function. It’s no coincidence that there is an isNaN, while isDefined is not present.

    An undefined identifier causes an error only if it’s not binded. If you bind it to its namespace, you can use it with the special “undefined” value. The “undefined” value is equivalent to “false” in conditional expressions.

    Let’s see an example. I want to assign an initial value to the “myvar” variable, but if it has been already defined somewhere then keep the old value.

    Let’s assume that myvar doesn’t exist.

    So this is incorrect:
    myvar = myvar ? myvar : newVal;

    You have to bind:
    myvar = window.myvar ? window.myvar : newVal;

    This can be shortened by this:
    myvar = window.myvar || newVal;

    Function parameters are also already binded:

    function something(par1) {
    myvar = par1 || newVal;
    }

    Or if you just want to know if something is defined, then:

    alert(”something = ” + (window.something || ‘not defined!’))

  7. #7 visitor
    1 year, 10 months ago

    All of the above methods did not work cross browser for me.

    IE 6 and FF1.5 version:
    function isDefined(object, variable){
    return (typeof((object)[variable]) == ‘undefined’)? false : true;
    }

    Have fun

  8. #8 Hakan
    1 year, 9 months ago

    “All of the above methods did not work cross browser for me.”

    • Isn’t enough that one of them work? All of them don’t need to work. It would be much worse if none of them worked.
  9. #9 Hakan
    1 year, 9 months ago

    Marton, thanks for that JavaScript. (Oh, by the way, you mean “bound”, not “binded”.)

  10. #10 saldi
    1 year, 7 months ago

    I’ve combined Marton and Dave’s function:

    function isDefined(variable)
    {
    return (!(!( variable||false )))
    }

  11. #11 someone
    1 year ago

    You are all fucking retards …
    I spent 2 hours trying to figure out what you did and in the end you did crap

  12. #12 ThisGuy
    11 months, 1 week ago

    someone: You spent 2 hours on this? Who’s the retard again?

  13. #13 anotherGuy
    10 months, 3 weeks ago

    I used these functions, which can easily be combined and simplified:

    function getTarget(targetRef) {
    if(typeof targetRef == ’string’) {
    targetRef = document.getElementById(targetRef);
    }
    return targetRef;
    }

    function exists(target) {
    var target = getTarget(target);
    if (target) return target;
    return false;
    }

  14. #14 Kenny
    10 months, 1 week ago

    Try this:

    if (typeof x==”undefined”){
    // variable x does not exist
    }

  15. #15 isDefined() en Javascript | aNieto2K
    9 months, 3 weeks ago

    […] Hace unos días, me encontré un post en Digg, que hablaba sobre la función isDefined() portada de ColdFusion a Javascript. En el mismo post de Jehiah Czebotar, se proponen alternativas y diferentes métodos de detectar de una variable está definida o no. […]

  16. #16 Jake
    9 months, 3 weeks ago

    Be careful with the default operator (||). It does type conversion and so will silently convert zero, false, the empty string and NaN to the default.

    var undef = undefined || “Correct”;
    var nil = null || “Correct (imho)”;
    var untrue = false || “Incorrect”;
    var zero = 0 || “Incorrect”;
    var NaN = Number(undefined) || “Incorrect”;
    var empty = “” || “Incorrect”;

  17. #17 Adrian Lynch
    9 months, 1 week ago

    So did we settle on a cross-browser solution? :O)

  18. #18 IYS
    9 months ago

    I just use

    typeof(x) == “undefined”

    some jscript implementations throw an error if you attempt to pass an undefined variable as a parameter. To me that says a cross-browser/cross-platform “isDefined” function isn’t actually possible.

  19. #19 Broadsmile
    7 months, 2 weeks ago

    I’m a lame, but can’t You do:

    try{ var local = global } catch(e) { var local = “default” }
    alert (local);

    ?

  20. #20 Broadsmile
    7 months, 2 weeks ago

    Oh, I’m sorry, I lost the thread :P

    I mean:

    try { var exists = (global != undefined) }
    catch(e) { var exists = false }
    if (exists) alert (global);

  21. #21 ArkeGuru
    6 months, 2 weeks ago

    try catch is a very slow operation and shouldn’t ever be used as a means of normal program flow.

  22. #22 Mithilesh
    5 months ago

    Hi,

    i tried all of your methids but not found what i am looking for ?

    id that correct :

    function showhidehide()
    {
    var oElement=document.fromlogin.member_type;
    if(oElement==”undefined”)
    {
    oElement.style.visibility = “hidden”;
    }
    }

  23. #23 RBraxton
    4 months ago

    What about:

    if(foo===undefined)doSomething()

  24. #24 Jehiah
    4 months ago

    @RBraxton, In javascript undefined is not something you can compare against directly, it is a string that is returned by the function call typeof which is why you do typeof(foo) == 'undefined'

    @Mithilesh you are also missing the typeof function, and i think you also are looking for !=

    @Dave, @Dan, others be very careful with javascript. It is case sensitive so isdefined() is not the same as isDefined(). Given my function above, one will work, the other will not. (partially my fault for making the title of the page different from my function)

  25. #25 David
    3 months, 1 week ago

    @Jehiah

    In javascript undefined is not something you can compare against directly

    Not true. undefined is an object. You can compare against it using === or !==.

    As long as you know foo is declared (e.g. as a param or var) then foo === undefined is the same as typeof(foo) == ‘undefined’

    However, I agree typeof is the best general solution because that also deals with cases where you can’t be sure whether the thing you’re testing is even declared (e.g. you’re testing to see whether some other js file is loaded).

  26. #26 Steve C.
    2 months, 3 weeks ago

    Just try this to prove what David says in post #25:
    document.writeln(”Are they equal? ” +
    (
    (typeof(stale.bread)==”undefined”) == (stale.bread===undefined)
    )
    );

  27. #27 DRY_GIN
    1 month, 2 weeks ago

    so why don’t just use

    if( whatever !==undefined) do_whatever

    without any functions ?
    passing undefined values or objects to functions causing more problems when the action itself

    or use inline statements like

    myval is undefined:

    a=50 + (myval===undefined)?0:myval + 100 +200;

    or somethin like that

  28. #28 HUMBERTHP
    1 month, 1 week ago

    para verificar si una variable está definida o no, use el siguiente script (En este caso para la variable popupWindow):

    if(typeof(popupWindow) != “undefined”){
    popupWindow.close();
    }

  29. #29 Autochton
    1 month ago

    @Jake: There’s no such thing as a ‘default’ operator. || is simply boolean or, and since each of your examples evaluates to false when read as a boolean, you’ll get the right-hand operand. If you want to check and set a default, use:

    function foo(arg1) {
    if ( ! [one of the abovementioned methods for checking if a var is defined] ) arg1 = “default”;
    [do whatever]
    }

Leave a comment