Tuesday, 6 January 2015

Does using == in JavaScript ever make sense?

I'm going to make an argument for == 
JavaScript is a behaviourally* typed language. Things are treated based on what they can do and not their actual type. This is why you can call an array's .map method on a NodeList or on a jQuery selection set. It's also why you can do 3 - "5" and get something meaningful back - because "5" can act like a number.
When you perform a == equality you are comparing the contents of a variable rather than its type. Here are some cases where this is useful:
  • Reading a number from the user - read the .value of an input element in the DOM? No problem! You don't have to start casting it or worrying about its type - you can == it right away to numbers and get something meaningful back.
  • Need to check for the "existence" of a declared variable? - you can == null it since behaviourally null represents there is nothing there and undefined doesn't have anything there either.
  • Need to check if you got meaningful input from a user? - check if the input is false with the ==argument, it will treat cases the user has entered nothing or just white-space for you which is probably what you need.
Let's look at examples and explain them behaviourally:
'' == '0'           // got input from user vs. didn't get input - so false
0 == ''             // number representing empty and string representing empty - so true
0 == '0'            // these both behave as the number 0 when added to numbers - so true    
false == 'false'    // false vs got input from user which is truth - so false
false == '0'        // both can substitute for 0 as numbers - so again true

false == undefined  // having nothing is not the same as having a false value - so false
false == null       // having empty is not the same as having a false value - so false
null == undefined   // both don't represent a value - so true

' \t\r\n ' == 0     // didn't get meaningful input from user vs false number - true 
Basically, == is designed to work based on how primitives behave in JavaScript not based on what theyare. While I don't personally agree with this point of view there is definitely merit in doing it - especially if you take this paradigm of treating types based on behaviour language-wide.

* some might prefer the name structural typing which is more common but there is a difference - not really interested in discussing the difference here.