How to test for equality of functions in Javascript [duplicate] How to test for equality of functions in Javascript [duplicate] javascript javascript

How to test for equality of functions in Javascript [duplicate]


You could check whether the content of two functions is exactly the same by comparing the result of calling toString on them

 var foo = function() {    a = 1; };  var bar = function() {    a = 1; }; alert(foo.toString() == bar.toString());​

That will, however, fail if there is but one character that is different. Checking to see if two functions do the same thing, on the other hand, is pretty much impossible.


The problem is that there're different notions of equality on functions.

  • Reference equality. Functions are stored somewhere in memory, and start from a certain address. For two function names (which are essentially addresses inside) reference equality gives you true iff both names point to the same address. It's a matter when you assign one bar = foo. Reference equality is used in JavaScript.
  • Equality on source code as proposed in another answer. It won't work, if you change any character in function body. Also, toSource is currently (as of 2014) only available in Firefox, as it's not W3C standartized.
  • Syntactic equalities on source code. One could use abstract syntax trees to resist against modifications in spaces and comments. One could use alpha-equivalence (i.e. equivalence of functions, where variables are consistently renamed) as defined in lambda calculus, but also there is
  • Extensional equality, when functions are equal if they work the same way. There's a theorem stating that there's just no algorithm to check for extensional equality of functions, so it's certainly not the one you're searching for. Though, in some more advanced languages than JS there are
  • Intensional equality (where you either prove that functions are equal by hand or your program doesn't compile) and
  • Observational equality (this one is too advanced to explain).

So, take care of what you think equality is.


You can test to see whether two variables refer to the exact same function object, and you can convert functions to strings and see if they're really exactly the same, but trying to determine whether two functions do the exact same thing would be a little harder, or maybe a lot harder.

Running a pair of functions through a minifier would be interesting, because minifiers do a considerable amount of static analysis.