Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

IsDefined()? 1

Status
Not open for further replies.

mattquantic

Programmer
Mar 28, 2004
196
GB
Hi, I would like to pass a parameter to an included function, but not have to update all of my scripts that call it.

Is there an IsDefined function? I was going to count the arguments, but that is not that future proof...

M@)
 
I use the following to test:

Code:
if (typeof variableName == "undefined")

Jeff
 
Deciding to have a shot at writing an actual isDefined() function — wish I hadn't bothered now. ;-)

Any of you guys (you know who you are) got a solution for the scope problem demo'd below?

Code:
function isDefined( checkVar ) {

	return ( typeof window[ checkVar ] == "undefined" ? false : true );
}

alert( "window defined? " + isDefined( "window" ) );
alert( "nothing defined? " + isDefined( "nothing" ) );

function test() {

	var monkey = 1;
}

alert( "monkey defined? " + isDefined( "monkey" ) );

Is that the most counter-intuitive if() statement ever or what. Heheh.
 

>> Any of you guys got a solution for the scope problem demo'd below?

What scope problem? Are you talking about monkey being undefined? If you are, why is that a scope problem - monkey is a local variable, and so shouldn't be available globally.

Dan

 

Precisely. How to check if non-blobal variables are defined ...
 

Well - you would just use Jeff's test within the scope of the local variable, surely?

Testing anything outside its scope would always be fruitless, surely? ;o)

Dan
 
Yeah, of course the standard version still works.
Testing anything outside its scope would always be fruitless, surely?
Yeah, but that's not what would be happening is it. Think about it.


I don't think it's gonna work with functions anyways — certainly can't think of a way. But hey! - that's why I asked, right. ;-)
 
Mattquantic,

I'm never fond of creating globals when you actually want to pass a parameter.

You could add a new parameter to an existing function:

f(a,b) {...} becomes f(a,b,c) {...}

where inside f you can test on passing c:

function f(a,b,c) {
c = (c ? c : defaultValueFor_c)
...
}

or

function f(a,b,c) {
if(c) { ... code when passing c ... }
...
}

Hope that helps,

Boelem
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top