Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

better approach of finding a variable is function?

Tags:

javascript

Which one is better approach to find whether a variable is of type function

typeof(methodName) == typeof(Function)

or

typeof methodName === 'function'
like image 371
coure2011 Avatar asked Mar 23 '23 19:03

coure2011


2 Answers

There are two things going on here:

  1. Parentheses — typeof is an operator, not a function, don't use them
  2. Comparing to 'function' or typeof Function (which will always return 'function' unless someone is screwing around and overwriting native objects). Use the string, it requires less work and isn't subject to the aforementioned screwing around.

i.e. Use:

typeof methodName === 'function'
like image 84
Quentin Avatar answered Apr 01 '23 06:04

Quentin


The second one has better performance and used in many javascript library

like image 20
aztack Avatar answered Apr 01 '23 05:04

aztack