JS Tip: `== null` is my favorite use case of double equals



In Javascript, I normally use === (triple equals) 99% of the time. However, I've found that one of the great remaining use cases for == (double equals) is when I want to check whether the value is null or undefined.

// A variable that can be a number, `null` or `undefined`
let myAge = 42
myAge == null // false
myAge = null
myAge == null // true
myAge = undefined
myAge == null // true

// The triple equals version is more verbose
myAge = 42
myAge === null || myAge === undefined // false
myAge = null
myAge === null || myAge === undefined // true
myAge = undefined
myAge === null || myAge === undefined // true

I also use it a lot in TypeScript when the value is nullable and optional.

// The `age` argument is nullable and also optional
function isAdult(age?: number | null) {
  if(age == null) {
    throw new Error('You need to provide your age')
  }
  return age >= 18
}

Happy coding!