Why you need to use typeof to check if a function exists with vanilla JS
A couple of days ago I shared a technique for checking if a function exists before trying to run it.
if (typeof getPurchases === 'function') {
getPurchases(123);
}
One astute reader asked why we can’t just do this:
if (getPurchases) {
getPurchases(123);
}
Great question!
That works in some cases, but… if the variable was assigned to something other than a function—a string, number, or object, for example—you’d the if statement would validate as true and then you’d try to run something that wasn’t a function and get an error.
var myFunction = 'Some string';
// or...
var myFunction = 123;
// This validates as true
if (myFunction) {
// Since myFunction isn't a function, this would throw an error
myFunction();
}