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>
5 years, 2 months ago
Should be able to specify the object.
I use this:
function isdefined(object, variable)
{
return (typeof(eval(object)[variable]) == “undefined”)? false: true;
}
4 years, 7 months ago
a bit shorter:
function isdefined(object, variable)
{
return (typeof(eval(object)[variable]) != ‘undefined’);
}
4 years, 4 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 years, 3 months ago
the method of Dave doesn’t work for javascript variables:
myVar=’HELLO’;
alert(isDefined(myVar));
=> The method of anyguy is better.
3 years, 12 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.
3 years, 10 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!’))
3 years, 7 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
3 years, 6 months ago
“All of the above methods did not work cross browser for me.”
3 years, 6 months ago
Marton, thanks for that JavaScript. (Oh, by the way, you mean “bound”, not “binded”.)
3 years, 4 months ago
I’ve combined Marton and Dave’s function:
function isDefined(variable)
{
return (!(!( variable||false )))
}
2 years, 8 months ago
You are all fucking retards …
I spent 2 hours trying to figure out what you did and in the end you did crap
2 years, 7 months ago
someone: You spent 2 hours on this? Who’s the retard again?
2 years, 7 months 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;
}
2 years, 6 months ago
Try this:
if (typeof x==”undefined”){
// variable x does not exist
}
2 years, 5 months 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. [...]
2 years, 5 months 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”;
2 years, 5 months ago
So did we settle on a cross-browser solution? :O)
2 years, 5 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.
2 years, 3 months ago
I’m a lame, but can’t You do:
try{ var local = global } catch(e) { var local = “default” }
alert (local);
?
2 years, 3 months 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);
2 years, 2 months ago
try catch is a very slow operation and shouldn’t ever be used as a means of normal program flow.
2 years, 1 month 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”;
}
}
2 years ago
What about:
if(foo===undefined)doSomething()
2 years ago
@RBraxton, In javascript
undefinedis not something you can compare against directly, it is a string that is returned by the function calltypeofwhich is why you dotypeof(foo) == 'undefined'@Mithilesh you are also missing the
typeoffunction, 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 asisDefined(). 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)1 year, 11 months ago
@Jehiah
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).
1 year, 11 months ago
Just try this to prove what David says in post #25:
document.writeln(“Are they equal? ” +
(
(typeof(stale.bread)==”undefined”) == (stale.bread===undefined)
)
);
1 year, 9 months 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
1 year, 9 months 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();
}
1 year, 9 months 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]
}
1 year, 6 months ago
I just succeed in getting IE to admit that the expression nEvent.srcElement was undefined without throwing an error. In this case, nEvent.hasOwnProperty(“srcElement”) was true, but the undefined value had been assigned to nEvent.srcElement.
After several failed attempts, what finally prevented IE from throwing an error was this:
1 year, 4 months ago
Hi all, I use next simple workaround:
var temp;
if (myvar == temp){
–> undefined
}
1 year, 2 months ago
Viktar, thats beauty, I used your workaround with a var called “empty”, works great, thank god somebody made it freakin’ simple.
The rest of the guys are right I’m sure, but i just want the stupid thing to work.
1 year, 1 month ago
I think this is what you want:
var x;
var aClosure = {laugh: “haha”, snooze: “zzzz…”};
tellMe(“x”,this);
tellMe(“laugh”,aClosure);
tellMe(“cry”,aClosure);
function isDefined(prop,obj) { return prop in obj; }
function tellMe(prop,obj)
{
var s = prop + ” is ” + ( isDefined(prop,obj) ? “defined” : “undefined” );
alert(s);
}
1 year, 1 month ago
Also worth pointing out is the fact that ‘undefined’ (the variable) can be set to some defined value — this is a very bad situation!
1 year ago
The solution provided by Jim W (and previously by HUMBERTHP) seems to work best.
11 months, 2 weeks ago
I was hunting for an answer to there being a javascript equivelant to isdefined in perl for testing an array index.
I came across this place and cant believe the complete bullshit you lot are coming out with.
do you know how I solved it…
if(myVar[index]){do what ever;}
You lot are a bunch of idiots and I hope the caffine Algo update in google drops this pathetic thread!
11 months, 1 week ago
Yep… amazing bunch of posts here, showing that this is a real common Javascript issue that web developers are facing. Hey “Ayatollah” Bill, thanks for your great post, it is really smart to insult people like you do. You are a man of courtesy and respect… No doubt you still live in a cave. Check RFC1855.
10 months, 1 week ago
Anyone who suggests to anyone else to use eval in Javascript should be vomited on before being hung up by the balls, and then let their arteries bleed out. What a bunch of fucking idiots! Losers.
8 months, 3 weeks ago
In IE (which is all I’m interested in right now), I found that
if (typeof(myVar) != “undefined”){…} works fine. Note: RFC1855 in an earlier post refers to etiquette on the net. As a friend taught me many years ago, there is no such thing as a stupid question (or stupid answer). I learn from everyone’s mistakes (including my own). If Einstein could learn something from a child (or novice), so can I.
7 months, 2 weeks ago
[...] did not work for testing a variable directly. I ended up following the advice of this post, Javascript IsDefined Function. To test if a variable is defined I now do [...]