javascript isset()

Have you ever wanted to test the existance of a javascript variable
(an array item for example) ?
Just like in PHP, I’ve found a method to do this.

The function returns true if the variable is set or false if the variable was not set.
A variable to be set must be initialized.
The starting point was that an unitialized variable has the type ‘undefined’.

A basic method can look like this:




Code (javascript)



function isset(varname){

return(typeof(varname)!=‘undefined’);

}

 


Some problems appear with this implementation, as Glen reported.



One problem is that when you pass an undefined variable, javascript throws an exception.

The other problem is that function member names can mess up the detection. (ex: pop() for array)

So here is a modified version. Please note the try/catch trick:



Code (javascript)


<script type="text/javascript">


function isset(varname)


{

try

{

var t = typeof(varname);

}

catch(e) {return false;}



if(t!==‘undefined’ && t != ‘function’) return true;

else

 return false;


}


var global_var = new Array();


function test()

{

var local_var = "xx";



try

{          

document.writeln("Test for function name (should be false) global_var[\"pop\"].Answer: " + isset(global_var["pop"]) + "


"
); // returns false - as global_var.pop() is a function

}

catch(e) {alert(e) /*code for not set*/}


try

{          


document.writeln("Test for global var (should be true).\nAnswer: " + isset(global_var) + "

"
); // returns true as global_var is set

}

catch(e) {alert(e) /*code for not set*/}



try

{          

document.writeln("Test for defined local var (should be true).Answer: " + isset(local_var) + "

"
); // the script does not support testing local vars… always returns false


}

catch(e) {alert(e) /*code for not set*/}


try

{          

document.writeln("Test for bogus var which is not defined (should be false).Answer: " + isset(bogus) + "


"
); // returns false as bogus var is not defined

}

catch(e) {alert(e) /*code for not set*/}



}


test();



</script>

 


0 comments: