How do you tell if a function in JavaScript is defined?
I want to do something like this
function something_cool(text, callback) { alert(text); if( callback != null ) callback(); }
But it gets me a
callback is not a function
error when callback is not defined.
You're Calling the Function Before It's Defined If the code that calls your JavaScript function precedes that function's definition in your HTML document, you will come across the function is not defined error.
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.
Use an if Conditional Statement The code in the brackets will execute if the function is defined. If instead you just test the function without using the window object, for example as if(aFunctionName) , JavaScript will throw a ReferenceErorr if the function doesn't exist.
To check if a particular function name has been defined, you can use JavaScript’s typeof operator: In our case, the typeof operator will return the string “undefined” because bad_function_call has not been defined.
Check if a JavaScript function exists before calling it. To check if a particular function name has been defined, you can use JavaScript’s typeof operator: //Use the typeof operator to check if a JS function exists. In our case, the typeof operator will return the string “undefined” because bad_function_call has not been defined.
Knowing the possible states of variables, let's consider the techniques to find whether a variable is defined or not. The typeof operator determines the variable's type. typeof myVar can evaluate to one of the values: 'boolean', 'number', 'string', 'symbol', 'object', 'function' and 'undefined'.
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. If you wish not to use jQuery for whatever reason, here's a barebones function based on code from Idealog that will check if the variable is of type function.
typeof callback === "function"
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