isset in Javascript
Here's another quick post regarding isset in Javascript.
How do you know if a Javascript variable has been set?
In PHP, this could easily be solved by using the native isset function:
if (isset($var))
{
echo 'The variable, $var has been set';
}
else
{
echo 'The variable, $var has not been set';
}
In Javascript, it's much more complex than that.
function isset(variable)
{
return (typeof(variable) != 'undefined');
}
The logic behind this function is that, if you access a missing element, you will get the undefined value.
Wasn't that quick?
Categories: Web Development
Tags: javascript
7 Comments
de
slink
It’s a bad manner to wrap type checking in a function since you get a reference error immediately as you call `?sset(any_undefined_var)`.
js> foo
ReferenceError: foo is not defined
js> function bar() {}
js> bar(foo)
ReferenceError: foo is not defined
December 18th 2009
slink
I missed to mention an important note: your solution is working as long as you introduced the variable with `var` keyword.
December 18th 2009
Insane
I think it´ll be usefull add a second parameter that indicates the scope on wich the var will be searched , by default ‘window’... and Slink is right, as soon as you try to acces to any undefined/unseted var you will get an error, I think the best workaround for the problem could be somenthing like this:
function isset(variableName,scope){
if(!scope) scope = window;
return (scope[variableName] && typeof(scope[variableName]) != ‘undefined’);
}
if(isset(‘myCore’)){
document.write(“Core loaded”);
}
December 19th 2009
Andrew Velis
The functionality does work in performing a type check. However I believe the approach is all wrong. You should know what variables you should be calling in any piece of code. That is to say any variable that is called should at least be defined first. Preferably to null because it evaluates to false in an if check. My suggestion is to feed your JS source through a JSLint (http://www.jslint.com/). It will definitely give you a better understanding of the troublesome areas in your code.
December 19th 2009
Achshar
Thanks. benn loking for this
February 11th 2010
sdf
sadsadsad
December 8th 2009