JavaScript: Function or Not?
In JavaScript, functions are first-class citizens, meaning they can be treated like any other variable: assigned to variables, passed as arguments, and returned from other functions. Being able to reliably determine if a given value is indeed a function is crucial for writing robust and dynamic code, especially when dealing with callbacks, event handlers, or dynamic module loading.
Problem Description
Your task is to write a JavaScript function, isFunction, that takes a single argument value. This function should return true if the value is a function, and false otherwise. You need to ensure your solution correctly identifies various types of functions and handles non-function values appropriately.
Key Requirements:
- The
isFunctionfunction must accept any JavaScript value. - It must return a boolean:
truefor functions,falsefor everything else. - Consider standard function declarations, function expressions, arrow functions, and built-in functions.
Expected Behavior:
isFunction(function() {})should returntrue.isFunction(() => {})should returntrue.isFunction(console.log)should returntrue.isFunction('hello')should returnfalse.isFunction(123)should returnfalse.isFunction(null)should returnfalse.isFunction(undefined)should returnfalse.isFunction({})should returnfalse.
Edge Cases to Consider:
- What about
Functionobjects created with theFunctionconstructor? - How does
typeofbehave withnullandundefined?
Examples
Example 1:
Input: function myFunc() { return 'test'; }
Output: true
Explanation: A standard function declaration is correctly identified as a function.
Example 2:
Input: const arrowFunc = () => 'arrow';
Output: true
Explanation: An arrow function is also correctly identified.
Example 3:
Input: 'This is a string'
Output: false
Explanation: A string is not a function.
Example 4:
Input: null
Output: false
Explanation: null is a primitive value, not a function.
Example 5:
Input: new Function('return "dynamic"')
Output: true
Explanation: Functions created via the Function constructor should be recognized.
Constraints
- The
isFunctionfunction should have no side effects. - The solution should be efficient and not computationally expensive.
- Input
valuecan be any valid JavaScript type.
Notes
Think about the typeof operator in JavaScript. While it's a good starting point, it has certain nuances. Consider how typeof behaves with different types, and if there are any other mechanisms or properties you can leverage for a more robust check. You might also consider the instanceof operator, but remember that it has its own limitations.