Hey anyone out there that uses JavaScript in a professional environment. I wanted to know the standard when comparing values using == and === operators. I was watching a video the explained that if you compared a sting with a value of ‘5’ and an int with a value of 5 it returns true using the == operator. They then suggested to use the === for everything. I know this is wrong because what if you wanted to compare some value nested in some polymorphic objects with different type defs say one being a student and the other being an instructor the === would always return false.
After much thought I came to the conclusion that it might be best to use === whenever possible and the == when only necessary.
Can you give me some insight on what the rule of thumb is in a professional environment?
The rule is simple:
Always use
===and!==unless you explicitly WANT a type conversion to be allowed and have thought through the consequences of that type conversion. In otherwords, you should be using===and!==nearly all the time.Your exception for polymorphic objects does not apply because
==and===both require two objects to be the exact same object when comparing two objects. There are no type conversions in that case. If you were comparing two properties of polymorphic objects, then only the type of the property is looked at, not the type of the containing object.For detailed rules on type conversions with
==, see this http://es5.github.com/#x11.9.3. There are some odd ones like this: