Hone logo
Hone
Problems

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 isFunction function must accept any JavaScript value.
  • It must return a boolean: true for functions, false for everything else.
  • Consider standard function declarations, function expressions, arrow functions, and built-in functions.

Expected Behavior:

  • isFunction(function() {}) should return true.
  • isFunction(() => {}) should return true.
  • isFunction(console.log) should return true.
  • isFunction('hello') should return false.
  • isFunction(123) should return false.
  • isFunction(null) should return false.
  • isFunction(undefined) should return false.
  • isFunction({}) should return false.

Edge Cases to Consider:

  • What about Function objects created with the Function constructor?
  • How does typeof behave with null and undefined?

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 isFunction function should have no side effects.
  • The solution should be efficient and not computationally expensive.
  • Input value can 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.

Loading editor...
javascript