w3resource

JavaScript: Check whether the given argument is a function

JavaScript fundamental (ES6 Syntax): Exercise-198 with Solution

Check If Function

Write a JavaScript program to check whether the given argument is a function.

  • Use typeof to check if a value is classified as a function primitive.

Sample Solution:

JavaScript Code:

// Define a function 'isFunction' that checks if the given value 'val' is a function
const isFunction = val =>
  // Check if the type of the given value 'val' is 'function'
  typeof val === 'function';

// Test cases to check if the values are functions
console.log(isFunction('x'));      // false (the value is not a function)
console.log(isFunction(x => x));   // true (the value is a function)

Output:

false
true

Flowchart:

flowchart: Check if the given argument is a function

Live Demo:

See the Pen javascript-basic-exercise-198-1 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that returns true if the provided argument is a function using typeof.
  • Write a JavaScript function that tests whether a variable is callable by checking its constructor and prototype.
  • Write a JavaScript program that distinguishes functions from objects by using Object.prototype.toString().
  • Write a JavaScript function that validates an input and logs a message if it is not a function.

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to check whether a string is lower case or not.
Next: Write a JavaScript program that will return true if the given number is even, false otherwise.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.