Javascript comparison

Javascript has some weired parts. Javascript performs type conversions, when two different types of values are compared.

Comparing primitives

Javascript has three primitive types string,boolean number. When a string is compared with a number ,String is converted to number using Number () function.

If we compare string with boolean, multiple type conversions are involved. First string is converted to number using Number() function and then boolean value is converted to number using Number() function.


When a number is compared to boolean, boolean value is converted to number using Number function.

Object Comparison

When a object is compared to a primitive type, object’s valueOf() is called to get the primitive Value of it. If there is no primitive value returned, object’s to string method is called.

By default valueOf() on a object returns the object itself if you don’t override it.

calling toString() on an array returns the string of comma seperated elements. So empty array’s tostring will return empty string.

Conclusion

Implicit type conversion may cause some serious bugs which will be hard to find. Follow the best practises.Use javascript in strict mode and === while making a comparison to avoid type conversion