What is the correct way to check if a JS function exists?
I’m told that typeof works but isn’t a very good way to do it.
Also, this doesn’t work:
if( function_name ) {
function_name();
}
What is the correct way to check if a JS function exists?
I’m told that typeof works but isn’t a very good way to do it.
Also, this doesn’t work:
if( function_name ) {
function_name();
}
As far as I know, typeof is both good and standard. Did the person who said otherwise give a reason?
No, which is why I thought to check.
Considering ‘typeof’ works, but ‘if(function_name)’ doesn’t then typeof is good enough for me!
Do you have a test case where if(function_name) doesn’t work?
var yep = function() {}
if (yep) { console.log('yep') }
else { console.log('nope') }
If you don’t use typeof then you will not know if a function by that name exists - the name might be being used for something else. It might even be being used but contain a value that returns false.
var yep = {} // an object instead of a function
if (yep) { console.log('yep') } // incorrect response
else { console.log('nope') }
The safest way to test is:
if (typeof yep==='function')
That way if the name exists but isn’t a function your subsequent processing will still work correctly.
As an actual example of where just testing the name wouldn’t work - I have a calendar script where you can either supply an object containing a list of holiday dates or supply a function that will generate the object. By testing whether the value passed is a function or not the code can run the function to generate the object. Simply testing if the field exists wouldn’t work since both an object and a function would return true for that test.
Sure do.
if (yep) { console.log('yep') }
else { console.log('nope') }
This results in an error: “yep is not defined”
Of course, really this only happens because “yep” wasn’t declared with “var”. So instead of typeof, you could also do this.
// if yep exists, then re-declaring it won't do any harm
// if yep doesn't exist, then we declare it for the first time
var yep;
if (yep) { console.log('yep') }
else { console.log('nope') }
In strict JavaScript the code would just fail to run completely (since in strict JavaScript all variables MUST be defined) and so wouldn’t generate the error.