How do I compare 2 functions in javascript? I am not talking about internal reference. Say
var a = function(){return 1;}; var b = function(){return 1;};
Is it possible to compare a
and b
?
This means you can test to see if your functions are exactly the same, including what spaces and newlines you put in it. But first you have to eliminate the difference in their names. function foo1() { return 1; } function foo2() { return 1; } //Get a string of the function declaration exactly as it was written.
The === operator compares operands and returns true if both operands are of same data type and have some value, otherwise, it returns false. The !== operator compares operands and returns true if both operands are of different data types or are of the same data type but have different values.
Comparing objects is easy, use === or Object.is(). This function returns true if they have the same reference and false if they do not. Again, let me stress, it is comparing the references to the objects, not the keys and values of the objects. So, from Example 3, Object.is(obj1,obj2); would return false.
Javascript Equals OperatorsThe non-strict equals operator (==) determines if two values are effectively equal regardless of their data type. The strict equals operator (===) determines if two values are exactly the same in both data type and value.
var a = b = function( c ){ return c; }; //here, you can use a === b because they're pointing to the same memory and they're the same type var a = function( c ){ return c; }, b = function( c ){ return c; }; //here you can use that byte-saver Andy E used (which is implicitly converting the function to it's body's text as a String), ''+a == ''+b. //this is the gist of what is happening behind the scences: a.toString( ) == b.toString( )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With