Check if a variable is of function type
Verify if your variable is a function using:
The typeof
operator performs a speedy, up-front function type verification.
The good, the bad, and the typeof
typeof
is a solid choice for quickly checking if a variable is a function. It's as reliable as getting fries with a burger. Yet, caution is needed. Put a wrong letter in your comparison, and you've got a silent failure brewing, much like a typo in your CSS making your page into abstract art:
Function: A tale of two checks
When typeof
feels too mainstream, swing to the beat of instanceof
. This operator is great for checking functions even from different realms, just like recognizing a cola no matter the brand:
For a more explicit check, dial Object.prototype.toString
. But be warned, it's a bit picky and won't recognize your modern async, generator, or proxied functions:
When libraries hold the answers
If you are a fan of Lodash or Underscore.js, they have a nifty _.isFunction()
method. It's like having a personal assistant to check your variables:
These libraries go the extra mile, checking for more edge cases.
Navigating the function jungle
Framework general store
Some frameworks like Angular come with helper functions such as angular.isFunction()
which are optimized and reliable under framework conditions. Use them if your code stays within the ecosystem.
Ghost of libraries past
Stay away from deprecated methods like .isFunction()
from jQuery post-3.3 and util.isFunction()
deprecated in Node.js v4.0.0. It's like using Windows 95 in 2022!
Warp speed checks
Running code in warehouses or mars rovers? Then every millisecond counts! Use benchmarks like https://jsben.ch/B6h73
to choose the most efficient function check for your use-case.
Tips from the JavaScript trenches
Reusable gear
Wrap common checks in a reusable function. This makes your code DRY and avoids repeating checks:
Handle with care
When calling a function dynamically, always use try-catch
to prevent script halts due to unexpected errors:
Different realms, different rules
In JavaScript, same-origin policy extends to execution context too. instanceof
can incorrectly judge functions from different frames or windows. Object.prototype.toString
or utility checks should be your safety net for such cases.
Was this article helpful?