By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,987 Members | 997 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,987 IT Pros & Developers. It's quick & easy.

How to check if a JS function is defined?

P: n/a
Hello,

What is a cross-browser way to check if a function has been defined?

It seems that this code

if (myFn) {
myFn();
}

executes whether myFn is defined or not. When it is not, a JS error
results.

Your help is greatly appreciated, - Dave

Jan 17 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Ivo
<la***********@zipmail.com> wrote
What is a cross-browser way to check if a function has been defined?
It seems that this code

if (myFn) {
myFn();
}

executes whether myFn is defined or not. When it is not, a JS error
results.


I don't see how that seems, but have you tried this if statement:
if ( typeof myFn==='function' )
--
ivo
http://4umi.com/web/javascript/

Jan 17 '06 #2

P: n/a
la***********@zipmail.com wrote:
Hello,

What is a cross-browser way to check if a function has been defined?

It seems that this code

if (myFn) {
myFn();
}

executes whether myFn is defined or not. When it is not, a JS error
results.


Use typeof:

function someFn(){}

function isFn(funcRef)
{
return 'function' == typeof funcRef;
}

alert('Is someFn a function? ' + isFn(someFn) );

--
Rob
Jan 17 '06 #3

P: n/a
RobG wrote:
la***********@zipmail.com wrote:
What is a cross-browser way to check if a function has been defined?
[...]


Use typeof:

function someFn(){}

function isFn(funcRef)
{
return 'function' == typeof funcRef;
}

alert('Is someFn a function? ' + isFn(someFn) );


Note that for host object's methods the `typeof' operation may evaluate to
"object" as well.
PointedEars
Feb 15 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.