Is the best approach to finding a variable a function?

Which one is better for determining if a variable is a function of type

typeof(methodName) == typeof(Function) 

or

 typeof methodName === 'function' 
+4
source share
5 answers

There are two things here:

  • Parentheses - typeof is an operator, not a function, don't use them
  • Comparison with 'function' or typeof Function (which will always return 'function' if someone does not spin and overwrite their own objects). Use a string, it requires less work and is not subject to the aforementioned screwing.

i.e. Using:

 typeof methodName === 'function' 
+5
source

The usual solution, which you will find, for example, in jQuery source code ( example ), is the second:

 typeof value === 'function' 

This is faster than the first, since you do not need to call the second typeof , and there is simply no reason to use the first as ECMAScript indicates that it should be a "function" :

enter image description here

+1
source

The second one has better performance and is used in many javascript libraries

+1
source

This is the best approach.

 if (typeof methodName === 'function') { // Do your stuff } 
0
source

The typeof operator returns a string indicating the type of the undirected operand. So this is correct -

 typeof methodName === 'function' 

See also: typeof

0
source

Source: https://habr.com/ru/post/1483288/


All Articles