TypeScript Bits are small, easily digestible pieces of information to encourage TypeScript/JavaScript best practices. From beginner, to intermediate, to ninja, these bits are for you 😄
Estimated reading time : 2 minutes
A very common point of confusion in JS/TS programming is what double equals and triple equals actually do. While this is base JS functionality, the method by how it works is quite simple (maybe) : Type Coercion
Because JavaScript is weakly typed, values can be easily converted from one type to another. Type Coercion is the implicit conversion from one type to another. There are only three types of conversion in Javascript to string, to boolean ,to number, allowing for "sameness" or "equality checking"
- Double Equals checks for sameness and performs Type Coercion prior to the equality operation
- Triple Equals checks for strict type and value equality without performing Type Coercion
it is easy to see the trouble one can get into
console.log("\n\t\r\n" == 0); // true
console.log("00000005" == 5); // true
console.log(0 == false); // true
desired equality outcomes
console.log("\n\t\r\n" === 0); // false
console.log("00000005" === 5); // false
console.log(0 === false); // false
WTNaN???
console.log(!NaN == true); // true
console.log(!NaN === true); // true!?!?!?
- IMPORTANT use ==, != when comparing a value or property with null or undefined (if allowed in linter), to ensure expected truthy/falsey with possibly null/undefined values
- Purists will suggest that double equals should never be used. However, this should be a configurable lint rule, deciding to use or not to use double equals by a team or enterprise.
- Type Coercion is invoked by many of the other operators (beware) <,<=,>,>=,~,!,+,-,*
- use typeof(x) === typeof(y) if you need to be certain beforehand
- If using defined types, in 99% of cases TS transpilation should fail and force correction (thus, use more TS and use it appropriately)
A great article that discusses Type Coercion here..