Skip to content

Instantly share code, notes, and snippets.

@kamauwashington
Last active September 4, 2022 23:31
Show Gist options
  • Save kamauwashington/3871c5f9c1e8e96c6027ea38fcaefdfc to your computer and use it in GitHub Desktop.
Save kamauwashington/3871c5f9c1e8e96c6027ea38fcaefdfc to your computer and use it in GitHub Desktop.

TypeScript Bits

Double vs Triple Equals

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

JS Sameness (Double Equals) in action

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

JS Strict Equality (Triple Equals) in action

desired equality outcomes

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

For fun, a brain teaser!

WTNaN???

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..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment