← All posts TypeScript Bits
KAMAU WASHINGTON
2 min read Novice September 5th, 2022

Double vs Triple Equals


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 before the equality operation.
  • Triple Equals checks for strict type and value equality without performing Type Coercion.

JS Sameness (Double Equals) in action

it is easy to see the trouble one can get into

javascript
console.log("\n\t\r\n" == 0); // true
console.log("00000005" == 5); // true
console.log(0 == false); // true

JS Strict Equality (Triple Equals) in action

desired equality outcomes

javascript
console.log("\n\t\r\n" === 0); // false
console.log("00000005" === 5); // false
console.log(0 === false); // false

For fun, a brain teaser!

WTNaN???

javascript
console.log(!NaN == true); // true
console.log(!NaN === true); // true!?!?!?

Notes

  • 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](https://www.freecodecamp.org/news/js-type-coercion-explained-27ba3d9a2839/#:~:text=Type%20coercion%20is%20the%20process,Symbol%20(added%20in%20ES6)…

Tagged javascriptnodejstype coerciontypescript