isset for javascript

I’ve just fruitlessly searched for an isset() function for javascript, so that I could create an empty array only if one doesn’t already exist.

So, for those of you that are also searching fruitlessly, here’s a way to do it:

try{
      if(variablename)blah=1/0;
}catch(e){
      variablename=[];
}

Fscking ugly, isn’t it?

Anyone know a better way?

23 Replies to “isset for javascript”

  1. Why don’t you use
    if (variablename == undefined)
    {
    variablename = [];
    }

    Some really old browsers don’t support undefined, but it will still work as long as you add a global def (with no value) for undefined, e.g.
    var undefined;

  2. Padraig – my answer to that is: d’oh! Maybe it’s not long enough for a proper Daily WTF, but I think that’s egg on my face…

  3. Padraig’s suggestion above was throwing exceptions with the current version of firefox, because “variablename” is in fact undefined. Here is a variant:

    Remember that variables defined in the global scope are properties of the “window” object. Here is a safe improvement to the code:

    if(undefined===window.variablename){
    window.variablename = [];
    }
    for some reason, firefox (with javascript debugging on) will complain with padraig’s code, but not this. Add that to the list of oddities of this strange, silly little language that is going to blow up with the oncoming “fat client” …. er … paradigm shift (ug).

    Note also my placement of the literal value on the left instead of right of the boolean operator (‘===’). I do this to protect against accidental assigment to an “lvalue” as newcomers frequently do when accidentally using the assignment operator instead (‘=’).

    Thanks all for the help. Someone should spearhead an effort to make a really well written JS faq / reference that is cross-browser compliant and answers questions for programmers coming from a background with mature languages.

    Blah blah blah. my email address is my first name then a dot then my last name at gmail dot com.

  4. function isset(varname){    if(typeof( window[ varname ] ) != “undefined”) return true;    else return false;}

  5. Formated:
    function isset(varname) {
    if(typeof( window[ varname ] ) != "undefined") return true;
    else return false;
    }

  6. ienliven, that could be written quicker as:
    function isset(varname){
    return(typeof(window[varname])!=’undefined’);
    }
    I haven’t tested it yet, but it looks right.

  7. Based on the articles original code, I use the following function.

    *note that the above suggestions that test against undefined and typeof will not work with the sample below*

    var foo = {};
    foo.bar = ‘value’;
    alert(‘foo.bar exists: ‘+isset(‘foo.bar’));

    isset = function(e) {
        try {
           if (eval(e)) {}
        }
        catch(err) {
           return false;
        }
        return true;
    }

  8. function isset(variable)
    {
        var undefined;
        return ( variable == undefined ? false : true );
    }That works fine for me in IE6 and FFMy usage was:function createElements()
    {
        var elArray = new Array();
        for ( var i = 0; i < createElements.arguments.length; i++ )
        {
            var el = createElements.arguments[i];
            if ( !isset(elArray[el]) )
            {
                elArray[el] = new Array();
            }
            elArray[el].push(document.createElement(el));
        }
        return elArray;
    }

  9. thanks for the info here

    if(undefined===window.variablename){

    window.variablename = [];

    }

    I have been looking for code like this far and wide…with no luck.
    I apply this to check if a login form exists on page. If it does, I add focus to it. Before, I had errors if it did not exist. But not with the above code added…
    Thanks again!
    k2a

  10. Javasctipt is ugly anyway… well javascript in itself maybe not so ugly, but once you start looking at the dom, dont get me started… i mean
    getelementbyid… firstsibling… offsetParent… lastChild… and then you have to add .value after everything… all that shit, like 50 functions to browse a stupid tree…

  11. miii : well at least there’s a structure which is, in fact, not that ugly if you try to understand it a little. But maybe counting to 50 is too much for some people…

  12. true. Besides, when was the last time you used “lastChild” or “firstSibling” ? I usually wrap my DOM access up in my own custom functions, to account for browser differences, etc, so I only ever really use familiar functions (which I wrote myself) on a daily basis.

    Personally, I believe the DOM is really a fantastic gift to programmers. I. for one, would not welcome a return to the dark ages of cross-browser differences.

  13. I think correct answer is –

    function isset(variable_name)
    {
    try
    {
    if (typeof(eval(variable_name)) != ‘undefined’)
    if (eval(variable_name) != null)
    return true;
    } catch(e) { }

    return false;
    }

    variable_name is a string param

  14. Is it possible to write an isset() function that can access the local scope of a function??

    function isset(varname) { return eval(‘typeof(‘ + varname + ‘) != “undefined”‘); }

    var1 = ‘test’; // global var

    function test()
    {
    var var2 = ‘test’; // local var
    alert(‘var1 isset() = ‘ + isset(‘var1’)); // true; global var
    alert(‘var2 isset() = ‘ + isset(‘var2’)); // false; local var
    alert(‘varname isset() = ‘ + isset(‘varname’)); // true; local var to isset()
    alert(‘arguments[0] isset() = ‘ + isset(‘arguments[0]’)); // true; local var to isset()
    }

    test();

    Assumptions based on tests:

    typeof(window[varname]) != ‘undefined’); can see only global scope, and gives no error
    typeof(eval(varname) != ‘undefined’); can see local scope of isset(), but gives an error if not defined
    eval(‘typeof(‘ + varname + ‘) != “undefined”‘); can see local scope of isset(), and gives no errors

    All of these scripts use one of the two, which can only access vars within the scope of the function.
    This includes local vars in isset() ie. varname, arguments[0] and global vars.

    This would be useful for testing argument input in functions.
    Yes, I can write out if(typeof(var1) != ‘undefined’) each time but I’m lazy.
    I’m also a PHP programmer and would like to use one set of terminology.

  15. Kirk, the local tests appear to be failing. in the first case (isset(‘var2’)), false is returned, and in the second case (isset(‘arguments[0]’)), that will always return true, as arguments[0] is the string “arguments[0]” (the first argument of the function isset()).

    Also, isset(‘varname’) will always return true, as it is set in the isset() function, and so is not properly tested (what if it was set in the test() function?).

    Or am I missing something?

  16. ‘varname’ and ‘arguments[0]’ are both local vars to isset(), not the test(). var2 is the only one that fails because it is not defined within the scope of isset() (includes global scope). I don’t think there’s any method that would allow you to access the local vars of the test(). The reason I put argument[0] in the list, is so that no one has misconception of isset() working for local vars using arguments[0]. it will always be true in any function if an argument is set. Basically, the main use of isset(), to check what parameters were entered into a function test(), appears to be impossible to achieve in js as isset() has no access to test()’s local variable (this includes test()’s arguments)

  17. Ok, well for all of you that need this, set the variable you plan to use, such as:

    string

    in the head section just put var string;

    then when you want to check the contents and see if it filled successfully,

    do: if (string.length) { } because string.length will return 0 which is false, and will return a number greater then 1 (which is true) if the variable has any text whatsoever in it, and works the same for an array, but will return the number of array elements inside not letters. enjoy 😉

Comments are closed.