I have a script on my website that calls a statically named function when called:
childLoad();
The childLoad()
function is not always defined though it is always called. How can I prevent the script from calling this function if it does not exist?
Please, some explanation. In two cases, simply call function_exists with the name of function parameter to check existence, returns bool.
To prevent the error, you can first check if a function exists in your current JavaScript environment by using a combination of an if statement and the typeof operator on the function you want to call.
With jQuery. isFunction() you may test a parameter to check if it is (a) defined and (b) is of type "function." Since you asked for jQuery, this function will tickle your fancy.
Sometimes when you're in the middle of a function, you want a quick way to exit. You can do it using the return keyword. Whenever JavaScript sees the return keyword, it immediately exits the function and any variable (or value) you pass after return will be returned back as a result.
if ( typeof childLoad == 'function' ) { childLoad(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With