Check if a variable is of function type

Suppose I have any variable, which is defined as follows:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var a = function() {/* Statements */};
</code>
<code>var a = function() {/* Statements */}; </code>
var a = function() {/* Statements */};

I want a function which checks if the type of the variable is function-like. i.e. :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>function foo(v) {if (v is function type?) {/* do something */}};
foo(a);
</code>
<code>function foo(v) {if (v is function type?) {/* do something */}}; foo(a); </code>
function foo(v) {if (v is function type?) {/* do something */}};
foo(a);

How can I check if the variable a is of type Function in the way defined above?

3

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>if (typeof v === 'function') {
// do something
}
</code>
<code>if (typeof v === 'function') { // do something } </code>
if (typeof v === 'function') {
    // do something
}

13

Sure underscore’s way is more efficient, but the best way to check, when efficiency isn’t an issue, is written on underscore’s page linked by @Paul Rosania.

Inspired by underscore, the final isFunction function is as follows:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}
</code>
<code>function isFunction(functionToCheck) { return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]'; } </code>
function isFunction(functionToCheck) {
 return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}

Note: This solution doesn’t work for async functions, generators or proxied functions. Please see other answers for more up to date solutions.

16

There are several ways so I will summarize them all

  1. Best way is:
    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code>function foo(v) {if (v instanceof Function) {/* do something */} };
    </code>
    <code>function foo(v) {if (v instanceof Function) {/* do something */} }; </code>
    function foo(v) {if (v instanceof Function) {/* do something */} };
    

    Most performant (no string comparison) and elegant solution – the instanceof operator has been supported in browsers for a very long time, so don’t worry – it will work in IE 6.

  2. Next best way is:
    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code>function foo(v) {if (typeof v === "function") {/* do something */} };
    </code>
    <code>function foo(v) {if (typeof v === "function") {/* do something */} }; </code>
    function foo(v) {if (typeof v === "function") {/* do something */} };
    

    disadvantage of typeof is that it is susceptible to silent failure, bad, so if you have a typo (e.g. “finction”) – in this case the if will just return false and you won’t know you have an error until later in your code

  3. The next best way is:
    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code>function isFunction(functionToCheck) {
    var getType = {};
    return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    }
    </code>
    <code>function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } </code>
    function isFunction(functionToCheck) {
        var getType = {};
        return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    }
    

    This has no advantage over solution #1 or #2 but is a lot less readable. An improved version of this is

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code>function isFunction(x) {
    return Object.prototype.toString.call(x) == '[object Function]';
    }
    </code>
    <code>function isFunction(x) { return Object.prototype.toString.call(x) == '[object Function]'; } </code>
    function isFunction(x) {
        return Object.prototype.toString.call(x) == '[object Function]';
    }
    

    but still lot less semantic than solution #1

5

Underscore.js uses a more elaborate but highly performant test:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>_.isFunction = function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
</code>
<code>_.isFunction = function(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); }; </code>
_.isFunction = function(obj) {
  return !!(obj && obj.constructor && obj.call && obj.apply);
};

See: https://jsben.ch/B6h73

EDIT: updated tests suggest that typeof might be faster, see https://jsben.ch/B6h73

7

jQuery (deprecated since version 3.3) Reference

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>$.isFunction(functionName);
</code>
<code>$.isFunction(functionName); </code>
$.isFunction(functionName);

AngularJS Reference

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>angular.isFunction(value);
</code>
<code>angular.isFunction(value); </code>
angular.isFunction(value);

Lodash Reference

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>_.isFunction(value);
</code>
<code>_.isFunction(value); </code>
_.isFunction(value);

Underscore Reference

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>_.isFunction(object);
</code>
<code>_.isFunction(object); </code>
_.isFunction(object); 

Node.js deprecated since v4.0.0 Reference

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var util = require('util');
util.isFunction(object);
</code>
<code>var util = require('util'); util.isFunction(object); </code>
var util = require('util');
util.isFunction(object);

@grandecomplex: There’s a fair amount of verbosity to your solution. It would be much clearer if written like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>function isFunction(x) {
return Object.prototype.toString.call(x) == '[object Function]';
}
</code>
<code>function isFunction(x) { return Object.prototype.toString.call(x) == '[object Function]'; } </code>
function isFunction(x) {
  return Object.prototype.toString.call(x) == '[object Function]';
}

4

Something with more browser support and also include async functions could be:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const isFunction = value => value ? (Object.prototype.toString.call(value) === "[object Function]" || "function" === typeof value || value instanceof Function) : false;
</code>
<code>const isFunction = value => value ? (Object.prototype.toString.call(value) === "[object Function]" || "function" === typeof value || value instanceof Function) : false; </code>
const isFunction = value => value ? (Object.prototype.toString.call(value) === "[object Function]" || "function" === typeof value || value instanceof Function) : false;

and then test it like:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>isFunction(isFunction); //true
isFunction(function(){}); //true
isFunction(()=> {}); //true
isFunction(()=> {return 1}); //true
isFunction(async function asyncFunction(){}); //true
isFunction(Array); //true
isFunction(Date); //true
isFunction(Object); //true
isFunction(Number); //true
isFunction(String); //true
isFunction(Symbol); //true
isFunction({}); //false
isFunction([]); //false
isFunction("function"); //false
isFunction(true); //false
isFunction(1); //false
isFunction("Alireza Dezfoolian"); //false
</code>
<code>isFunction(isFunction); //true isFunction(function(){}); //true isFunction(()=> {}); //true isFunction(()=> {return 1}); //true isFunction(async function asyncFunction(){}); //true isFunction(Array); //true isFunction(Date); //true isFunction(Object); //true isFunction(Number); //true isFunction(String); //true isFunction(Symbol); //true isFunction({}); //false isFunction([]); //false isFunction("function"); //false isFunction(true); //false isFunction(1); //false isFunction("Alireza Dezfoolian"); //false </code>
isFunction(isFunction); //true
isFunction(function(){}); //true
isFunction(()=> {}); //true
isFunction(()=> {return 1}); //true
isFunction(async function asyncFunction(){}); //true
isFunction(Array); //true
isFunction(Date); //true
isFunction(Object); //true
isFunction(Number); //true
isFunction(String); //true
isFunction(Symbol); //true
isFunction({}); //false
isFunction([]); //false
isFunction("function"); //false
isFunction(true); //false
isFunction(1); //false
isFunction("Alireza Dezfoolian"); //false

2

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const foo = function() {};
if (typeof foo === 'function') {
console.log('is function')
}</code>
<code>const foo = function() {}; if (typeof foo === 'function') { console.log('is function') }</code>
const foo = function() {};
if (typeof foo === 'function') {
  console.log('is function')
}

1

Try the instanceof operator: it seems that all functions inherit from the Function class:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// Test data
var f1 = function () { alert("test"); }
var o1 = { Name: "Object_1" };
F_est = function () { };
var o2 = new F_est();
// Results
alert(f1 instanceof Function); // true
alert(o1 instanceof Function); // false
alert(o2 instanceof Function); // false
</code>
<code>// Test data var f1 = function () { alert("test"); } var o1 = { Name: "Object_1" }; F_est = function () { }; var o2 = new F_est(); // Results alert(f1 instanceof Function); // true alert(o1 instanceof Function); // false alert(o2 instanceof Function); // false </code>
// Test data
var f1 = function () { alert("test"); }
var o1 = { Name: "Object_1" };
F_est = function () { };
var o2 = new F_est();

// Results
alert(f1 instanceof Function); // true
alert(o1 instanceof Function); // false
alert(o2 instanceof Function); // false

1

An other simply way:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var fn = function () {}
if (fn.constructor === Function) {
// true
} else {
// false
}
</code>
<code>var fn = function () {} if (fn.constructor === Function) { // true } else { // false } </code>
var fn = function () {}
if (fn.constructor === Function) {
  // true
} else {
  // false
}

2

For those who’s interested in functional style, or looks for more expressive approach to utilize in meta programming (such as type checking), it could be interesting to see Ramda library to accomplish such task.

Next code contains only pure and pointfree functions:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const R = require('ramda');
const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);
const equalsSyncFunction = isPrototypeEquals(() => {});
const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);
</code>
<code>const R = require('ramda'); const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals); const equalsSyncFunction = isPrototypeEquals(() => {}); const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction); </code>
const R = require('ramda');

const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);

const equalsSyncFunction = isPrototypeEquals(() => {});

const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);

As of ES2017, async functions are available, so we can check against them as well:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const equalsAsyncFunction = isPrototypeEquals(async () => {});
const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);
</code>
<code>const equalsAsyncFunction = isPrototypeEquals(async () => {}); const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction); </code>
const equalsAsyncFunction = isPrototypeEquals(async () => {});

const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);

And then combine them together:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const isFunction = R.either(isSyncFunction, isAsyncFunction);
</code>
<code>const isFunction = R.either(isSyncFunction, isAsyncFunction); </code>
const isFunction = R.either(isSyncFunction, isAsyncFunction);

Of course, function should be protected against null and undefined values, so to make it “safe”:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const safeIsFunction = R.unless(R.isNil, isFunction);
</code>
<code>const safeIsFunction = R.unless(R.isNil, isFunction); </code>
const safeIsFunction = R.unless(R.isNil, isFunction);

And, complete snippet to sum up:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const R = require('ramda');
const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);
const equalsSyncFunction = isPrototypeEquals(() => {});
const equalsAsyncFunction = isPrototypeEquals(async () => {});
const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);
const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);
const isFunction = R.either(isSyncFunction, isAsyncFunction);
const safeIsFunction = R.unless(R.isNil, isFunction);
// ---
console.log(safeIsFunction( function () {} ));
console.log(safeIsFunction( () => {} ));
console.log(safeIsFunction( (async () => {}) ));
console.log(safeIsFunction( new class {} ));
console.log(safeIsFunction( {} ));
console.log(safeIsFunction( [] ));
console.log(safeIsFunction( 'a' ));
console.log(safeIsFunction( 1 ));
console.log(safeIsFunction( null ));
console.log(safeIsFunction( undefined ));
</code>
<code>const R = require('ramda'); const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals); const equalsSyncFunction = isPrototypeEquals(() => {}); const equalsAsyncFunction = isPrototypeEquals(async () => {}); const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction); const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction); const isFunction = R.either(isSyncFunction, isAsyncFunction); const safeIsFunction = R.unless(R.isNil, isFunction); // --- console.log(safeIsFunction( function () {} )); console.log(safeIsFunction( () => {} )); console.log(safeIsFunction( (async () => {}) )); console.log(safeIsFunction( new class {} )); console.log(safeIsFunction( {} )); console.log(safeIsFunction( [] )); console.log(safeIsFunction( 'a' )); console.log(safeIsFunction( 1 )); console.log(safeIsFunction( null )); console.log(safeIsFunction( undefined )); </code>
const R = require('ramda');

const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);

const equalsSyncFunction = isPrototypeEquals(() => {});
const equalsAsyncFunction = isPrototypeEquals(async () => {});

const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);
const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);

const isFunction = R.either(isSyncFunction, isAsyncFunction);

const safeIsFunction = R.unless(R.isNil, isFunction);

// ---

console.log(safeIsFunction( function () {} ));
console.log(safeIsFunction( () => {} ));
console.log(safeIsFunction( (async () => {}) ));
console.log(safeIsFunction( new class {} ));
console.log(safeIsFunction( {} ));
console.log(safeIsFunction( [] ));
console.log(safeIsFunction( 'a' ));
console.log(safeIsFunction( 1 ));
console.log(safeIsFunction( null ));
console.log(safeIsFunction( undefined ));

However, note the this solution could show less performance than other available options due to extensive usage of higher-order functions.

0

If you use Lodash you can do it with _.isFunction.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>_.isFunction(function(){});
// => true
_.isFunction(/abc/);
// => false
_.isFunction(true);
// => false
_.isFunction(null);
// => false
</code>
<code>_.isFunction(function(){}); // => true _.isFunction(/abc/); // => false _.isFunction(true); // => false _.isFunction(null); // => false </code>
_.isFunction(function(){});
// => true

_.isFunction(/abc/);
// => false

_.isFunction(true);
// => false

_.isFunction(null);
// => false

This method returns true if value is a function, else false.

This is an old question but there are some considerations in 2022:

First, browser compatibility: instanceof is supported by all modern browsers as well as Deno and NodeJS.
Also, it’s syntactically readable and more friendly than typeof.
Finally, it provides a good performance over string comparison but is slower than typeof. Therefore, for me this is the a good option

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const fnc = () => {}
const isFunction = f => !!f && f instanceof Function
const isFunctionFaster = f => !!f && 'function' === typeof f
console.log({
isFunction: isFunction(fnc),
isFunctionFaster: isFunctionFaster(fnc),
})</code>
<code>const fnc = () => {} const isFunction = f => !!f && f instanceof Function const isFunctionFaster = f => !!f && 'function' === typeof f console.log({ isFunction: isFunction(fnc), isFunctionFaster: isFunctionFaster(fnc), })</code>
const fnc = () => {}
const isFunction = f => !!f && f instanceof Function
const isFunctionFaster = f => !!f && 'function' === typeof f

console.log({
  isFunction: isFunction(fnc),
  isFunctionFaster: isFunctionFaster(fnc),
})

Notice

It is important to understand that this is a optimized function for benchmarking. When you bench mark you want to pass all the test like null, undefined and some on possible parameters received. f && ... filter this null like parameters to reduce computation time.

  • Caveats of instanceof operator:

This operator tests the presence of constructor.prototype in the object’s prototype chain. This usually (though not always) means object was constructed with constructor. Therefore, this process is slower compared with typeof operator.

typeof v === ‘function’)

  • Caveats of typeof operator:

This operator returns a string indicating the type of the operand’s value. This is executed very fast.

  • Caveats of instanceof and typeof operators:

Remember that a class declaration, it’s also considered as a function by the these operators, as you can see in this snippet:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// Class Declaration
class A {}
// Instances
const obj = {}
const arr = []
const fnc = () => {}
const a = new A()
console.log('typeof')
console.log(`Object[${typeof Object}], obj[${typeof obj}]`)
console.log(`Array[${typeof Array}], arr[${typeof arr}]`)
console.log(`Function[${typeof Function}], fnc[${typeof fnc}]`)
console.log(`A[${typeof A}], a[${typeof a}]`)
console.log('instanceof')
console.log(`Object[${Object instanceof Object}], obj[${obj instanceof Object}]`)
console.log(`Array[${Array instanceof Array}], arr[${arr instanceof Array}]`)
console.log(`Function[${Function instanceof Function}], fnc[${fnc instanceof Function}]`)
console.log(`A[${A instanceof A}], a[${a instanceof A}]`)</code>
<code>// Class Declaration class A {} // Instances const obj = {} const arr = [] const fnc = () => {} const a = new A() console.log('typeof') console.log(`Object[${typeof Object}], obj[${typeof obj}]`) console.log(`Array[${typeof Array}], arr[${typeof arr}]`) console.log(`Function[${typeof Function}], fnc[${typeof fnc}]`) console.log(`A[${typeof A}], a[${typeof a}]`) console.log('instanceof') console.log(`Object[${Object instanceof Object}], obj[${obj instanceof Object}]`) console.log(`Array[${Array instanceof Array}], arr[${arr instanceof Array}]`) console.log(`Function[${Function instanceof Function}], fnc[${fnc instanceof Function}]`) console.log(`A[${A instanceof A}], a[${a instanceof A}]`)</code>
// Class Declaration
class A {}

// Instances
const obj = {}
const arr = []
const fnc = () => {}
const a = new A()

console.log('typeof')
console.log(`Object[${typeof Object}], obj[${typeof obj}]`)
console.log(`Array[${typeof Array}], arr[${typeof arr}]`)
console.log(`Function[${typeof Function}], fnc[${typeof fnc}]`)
console.log(`A[${typeof A}], a[${typeof a}]`)

console.log('instanceof')
console.log(`Object[${Object instanceof Object}], obj[${obj instanceof Object}]`)
console.log(`Array[${Array instanceof Array}], arr[${arr instanceof Array}]`)
console.log(`Function[${Function instanceof Function}], fnc[${fnc instanceof Function}]`)
console.log(`A[${A instanceof A}], a[${a instanceof A}]`)

Here is a basic sample of the isFunction and isFunctionFaster usage with different instances:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// Functions
const isNil = o => o == null
const isFunction = f => !!f && f instanceof Function
const isFunctionFaster = f => !!f && 'function' === typeof f
class A {}
function basicFnc(){}
async function asyncFnc(){}
const arrowFnc = ()=> {}
const arrowRFnc = ()=> 1
// Not functions
const obj = {}
const arr = []
const str = 'function'
const bol = true
const num = 1
const a = new A()
const list = [
isFunction,
isFunctionFaster,
basicFnc,
arrowFnc,
arrowRFnc,
asyncFnc,
Array,
Date,
Object,
Number,
String,
Symbol,
A,
obj,
arr,
str,
bol,
num,
a,
null,
undefined,
]
for (const arg of list) {
console.log(`${arg} is a function: ${isFunction(arg)}`)
}</code>
<code>// Functions const isNil = o => o == null const isFunction = f => !!f && f instanceof Function const isFunctionFaster = f => !!f && 'function' === typeof f class A {} function basicFnc(){} async function asyncFnc(){} const arrowFnc = ()=> {} const arrowRFnc = ()=> 1 // Not functions const obj = {} const arr = [] const str = 'function' const bol = true const num = 1 const a = new A() const list = [ isFunction, isFunctionFaster, basicFnc, arrowFnc, arrowRFnc, asyncFnc, Array, Date, Object, Number, String, Symbol, A, obj, arr, str, bol, num, a, null, undefined, ] for (const arg of list) { console.log(`${arg} is a function: ${isFunction(arg)}`) }</code>
// Functions
const isNil = o => o == null
const isFunction = f => !!f && f instanceof Function
const isFunctionFaster = f => !!f && 'function' === typeof f

class A {}

function basicFnc(){}
async function asyncFnc(){}

const arrowFnc = ()=> {}
const arrowRFnc = ()=> 1

// Not functions
const obj = {}
const arr = []
const str = 'function'
const bol = true
const num = 1
const a = new A()

const list = [
    isFunction,
    isFunctionFaster,
    basicFnc,
    arrowFnc,
    arrowRFnc,
    asyncFnc,
    Array,
    Date,
    Object,
    Number,
    String,
    Symbol,
    A,
    obj,
    arr,
    str,
    bol,
    num,
    a,
    null,
    undefined,
]

for (const arg of list) {
  console.log(`${arg} is a function: ${isFunction(arg)}`)
}

Here is a basic benchmark of these functions:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>/**
* Figure out how long it takes for a method to execute.
*
* @param {Function} method to test
* @param {number} iterations number of executions.
* @param {Array} args to pass in.
* @param {T} context the context to call the method in.
* @return {number} the time it took, in milliseconds to execute.
*/
const bench = (method, list, iterations, context) => {
let start = 0
const timer = action => {
const time = performance.now()
switch (action) {
case 'start':
start = time
return 0
case 'stop':
const elapsed = time - start
start = 0
return elapsed
default:
return time - start
}
};
const result = []
timer('start')
list = [...list]
for (let i = 0; i < iterations; i++) {
for (const args of list) {
result.push(method.apply(context, args))
}
}
const elapsed = timer('stop')
console.log(`Called method [${method.name}]`)
console.log(`Mean: ${elapsed / iterations}`)
console.log(`Exec. time: ${elapsed}`)
return elapsed
}
const fnc = () => {}
const isFunction = (f) => f && f instanceof Function
const isFunctionFaster = (f) => f && 'function' === typeof f
class A {}
function basicFnc(){}
async function asyncFnc(){}
const arrowFnc = ()=> {}
const arrowRFnc = ()=> 1
// Not functions
const obj = {}
const arr = []
const str = 'function'
const bol = true
const num = 1
const a = new A()
const list = [
[isFunction],
[basicFnc],
[arrowFnc],
[arrowRFnc],
[asyncFnc],
[Array],
[Date],
[Object],
[Number],
[String],
[Symbol],
[A],
[obj],
[arr],
[str],
[bol],
[num],
[a],
[null],
[undefined],
]
const e1 = bench(isFunction, list, 10000)
const e2 = bench(isFunctionFaster, list, 10000)
const rate = e2/e1
const percent = Math.abs(1 - rate)*100
console.log(`[isFunctionFaster] is ${(percent).toFixed(2)}% ${rate < 1 ? 'faster' : 'slower'} than [isFunction]`)</code>
<code>/** * Figure out how long it takes for a method to execute. * * @param {Function} method to test * @param {number} iterations number of executions. * @param {Array} args to pass in. * @param {T} context the context to call the method in. * @return {number} the time it took, in milliseconds to execute. */ const bench = (method, list, iterations, context) => { let start = 0 const timer = action => { const time = performance.now() switch (action) { case 'start': start = time return 0 case 'stop': const elapsed = time - start start = 0 return elapsed default: return time - start } }; const result = [] timer('start') list = [...list] for (let i = 0; i < iterations; i++) { for (const args of list) { result.push(method.apply(context, args)) } } const elapsed = timer('stop') console.log(`Called method [${method.name}]`) console.log(`Mean: ${elapsed / iterations}`) console.log(`Exec. time: ${elapsed}`) return elapsed } const fnc = () => {} const isFunction = (f) => f && f instanceof Function const isFunctionFaster = (f) => f && 'function' === typeof f class A {} function basicFnc(){} async function asyncFnc(){} const arrowFnc = ()=> {} const arrowRFnc = ()=> 1 // Not functions const obj = {} const arr = [] const str = 'function' const bol = true const num = 1 const a = new A() const list = [ [isFunction], [basicFnc], [arrowFnc], [arrowRFnc], [asyncFnc], [Array], [Date], [Object], [Number], [String], [Symbol], [A], [obj], [arr], [str], [bol], [num], [a], [null], [undefined], ] const e1 = bench(isFunction, list, 10000) const e2 = bench(isFunctionFaster, list, 10000) const rate = e2/e1 const percent = Math.abs(1 - rate)*100 console.log(`[isFunctionFaster] is ${(percent).toFixed(2)}% ${rate < 1 ? 'faster' : 'slower'} than [isFunction]`)</code>
/**
 * Figure out how long it takes for a method to execute.
 * 
 * @param {Function} method to test 
 * @param {number} iterations number of executions.
 * @param {Array} args to pass in. 
 * @param {T} context the context to call the method in.
 * @return {number} the time it took, in milliseconds to execute.
 */
const bench = (method, list, iterations, context) => {
    let start = 0
    const timer = action => {
        const time = performance.now()
        switch (action) {
            case 'start':
                start = time
                return 0
            case 'stop':
                const elapsed = time - start
                start = 0
                return elapsed
            default:
                return time - start
        }
    };

    const result = []
    timer('start')
    list = [...list]
    for (let i = 0; i < iterations; i++) {
      for (const args of list) {
        result.push(method.apply(context, args))
      }
    }
    const elapsed = timer('stop')
    
    console.log(`Called method [${method.name}]`)
    console.log(`Mean: ${elapsed / iterations}`)
    console.log(`Exec. time: ${elapsed}`)

    return elapsed
}

const fnc = () => {}
const isFunction = (f) => f && f instanceof Function
const isFunctionFaster = (f) => f && 'function' === typeof f


class A {}

function basicFnc(){}
async function asyncFnc(){}

const arrowFnc = ()=> {}
const arrowRFnc = ()=> 1

// Not functions
const obj = {}
const arr = []
const str = 'function'
const bol = true
const num = 1
const a = new A()

const list = [
    [isFunction],
    [basicFnc],
    [arrowFnc],
    [arrowRFnc],
    [asyncFnc],
    [Array],
    [Date],
    [Object],
    [Number],
    [String],
    [Symbol],
    [A],
    [obj],
    [arr],
    [str],
    [bol],
    [num],
    [a],
    [null],
    [undefined],
]

const e1 = bench(isFunction, list, 10000)
const e2 = bench(isFunctionFaster, list, 10000)

const rate = e2/e1
const percent = Math.abs(1 - rate)*100

console.log(`[isFunctionFaster] is ${(percent).toFixed(2)}% ${rate < 1 ? 'faster' : 'slower'} than [isFunction]`)

Conclusion

In general isFunctionFaster is faster than isFunction in 30%.

The below seems to work for me as well (tested from node.js):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var isFunction = function(o) {
return Function.prototype.isPrototypeOf(o);
};
console.log(isFunction(function(){})); // true
console.log(isFunction({})); // false
</code>
<code>var isFunction = function(o) { return Function.prototype.isPrototypeOf(o); }; console.log(isFunction(function(){})); // true console.log(isFunction({})); // false </code>
var isFunction = function(o) {
     return Function.prototype.isPrototypeOf(o);
};

console.log(isFunction(function(){})); // true
console.log(isFunction({})); // false

I found that when testing native browser functions in IE8, using toString, instanceof, and typeof did not work. Here is a method that works fine in IE8 (as far as I know):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>function isFn(f){
return !!(f && f.call && f.apply);
}
//Returns true in IE7/8
isFn(document.getElementById);
</code>
<code>function isFn(f){ return !!(f && f.call && f.apply); } //Returns true in IE7/8 isFn(document.getElementById); </code>
function isFn(f){
    return !!(f && f.call && f.apply);
}
//Returns true in IE7/8
isFn(document.getElementById);

Alternatively, you can check for native functions using:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>"getElementById" in document
</code>
<code>"getElementById" in document </code>
"getElementById" in document

Though, I have read somewhere that this will not always work in IE7 and below.

0

I think you can just define a flag on the Function prototype and check if the instance you want to test inherited that

define a flag:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Function.prototype.isFunction = true;
</code>
<code>Function.prototype.isFunction = true; </code>
Function.prototype.isFunction = true; 

and then check if it exist

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var foo = function(){};
foo.isFunction; // will return true
</code>
<code>var foo = function(){}; foo.isFunction; // will return true </code>
var foo = function(){};
foo.isFunction; // will return true

The downside is that another prototype can define the same flag and then it’s worthless, but if you have full control over the included modules it is the easiest way

1

you should use typeOf operator in js.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var a=function(){
alert("fun a");
}
alert(typeof a);// alerts "function"
</code>
<code>var a=function(){ alert("fun a"); } alert(typeof a);// alerts "function" </code>
var a=function(){
    alert("fun a");
}
alert(typeof a);// alerts "function"

Since node v0.11 you can use the standard util function :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var util = require('util');
util.isFunction('foo');
</code>
<code>var util = require('util'); util.isFunction('foo'); </code>
var util = require('util');
util.isFunction('foo');

1

if you are looking for a simple solution:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> function isFunction(value) {
return value instanceof Function
}
</code>
<code> function isFunction(value) { return value instanceof Function } </code>
 function isFunction(value) {
   return value instanceof Function
}

Becareful about this :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>typeof Object === "function" // true.
typeof Array === "function" // true
</code>
<code>typeof Object === "function" // true. typeof Array === "function" // true </code>
typeof Object === "function" // true.
typeof Array  === "function" // true

1

There are functions whose arguments can be passed either as a value or though a callback. To implement them a nice helper function that utilizes type detection is the following:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const toCallback = (v)=>(v instanceof Function)?v:()=>v
</code>
<code>const toCallback = (v)=>(v instanceof Function)?v:()=>v </code>
const toCallback = (v)=>(v instanceof Function)?v:()=>v

Then let’s say you want to implement a function that can receive either a fixed value or a callback that returns the value. See below:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>let someFunction=(valueOrFunction)=>{
let f = toCallback(valueOrFunction);
[1,2,3].forEach(v=>console.log(`value passed: ${f()}`))
}
</code>
<code>let someFunction=(valueOrFunction)=>{ let f = toCallback(valueOrFunction); [1,2,3].forEach(v=>console.log(`value passed: ${f()}`)) } </code>
let someFunction=(valueOrFunction)=>{
    let f = toCallback(valueOrFunction); 
    [1,2,3].forEach(v=>console.log(`value passed: ${f()}`))   
}

and now you can execute the above in two ways:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>someFunction(5);
//value passed: 5
//value passed: 5
//value passed: 5
someFunction(()=>Math.random());
//value passed: 0.3218832537523002
//value passed: 0.2343617971814611
//value passed: 0.38216627030533656
</code>
<code>someFunction(5); //value passed: 5 //value passed: 5 //value passed: 5 someFunction(()=>Math.random()); //value passed: 0.3218832537523002 //value passed: 0.2343617971814611 //value passed: 0.38216627030533656 </code>
someFunction(5);
//value passed: 5
//value passed: 5
//value passed: 5

someFunction(()=>Math.random());
//value passed: 0.3218832537523002
//value passed: 0.2343617971814611
//value passed: 0.38216627030533656

This is a bit tricky question as you need to define “what is a function?” first.
Let’s look at node (V8 implementation of JavaScript engine). It is written in C++ but also has parts in JavaScript.
Some functions are magically mapped to C++ functions. Those do not have all the properties of standard function.
Other functions are simply JavaScript functions with prototype set to null. It means they don’t inherit from Object and wouldn’t have methods such as toString() and similar.
Then finally you have standard instances of Function.
And there is also AsyncFunction which is a Function but a bit different.
Think what about a promise that returns a function – is it a Function or rather a Promise? Is Promise a Function?

This told let’s see how node implements checking if an argument is an AsyncFunction:
readable-stream defined AsyncFunction as a prototype of async function.
Then type check is simply typeof arg === 'function' as seen here.

  • You need to define “what is a function” first
  • If you understand it as an instance of some class then you can use for example arg instanceof Function which returns a boolean
  • If you wish to see what the function inherits from then you could check its prototype
  • If you define anything that can be called a function – check if it is callable
  • There are still some issues with that 🙁
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// It doesn't really matter if you use named function or not - but that is cool to know that it can have a name :)
let f = function aNamedFunction(){console.log('hello')};
f.prototype = null;
console.log(f instanceof Function, typeof f); // true, function
f.__proto__ = null;
console.log(f instanceof Function); // false, function
console.log(Object.getOwnPropertyNames(f)); // prototype, length, name
f(); // 'hello'
</code>
<code>// It doesn't really matter if you use named function or not - but that is cool to know that it can have a name :) let f = function aNamedFunction(){console.log('hello')}; f.prototype = null; console.log(f instanceof Function, typeof f); // true, function f.__proto__ = null; console.log(f instanceof Function); // false, function console.log(Object.getOwnPropertyNames(f)); // prototype, length, name f(); // 'hello' </code>
// It doesn't really matter if you use named function or not - but that is cool to know that it can have a name :)
let f = function aNamedFunction(){console.log('hello')};
f.prototype = null;
console.log(f instanceof Function, typeof f); // true, function
f.__proto__ = null;
console.log(f instanceof Function); // false, function
console.log(Object.getOwnPropertyNames(f)); // prototype, length, name
f(); // 'hello'

To summarize:
The typeof arg === 'function' seems pretty good (though there are few fancy scenarios where it would fail).

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật