DEV Community

Discussion on: Clean up your code with these tips!

Collapse
 
qm3ster profile image
Mihail Malo

So then, something like this?

typeof window !== "undefined" &&
  window.hasOwnProperty("location") &&
  window.location.hostname

I guess.

It's actually really unclear how to do such checks, you have to keep in mind what failures you actually expect to have.
On one hand, if you expect an object, truthiness gets rid of null, undefined, false (we'd be getting the false from the typeof equality, as well as hasOwnProperty) as well as less importantly 0, and "".

// OH NO
;({ location: undefined }.hasOwnProperty("location")) // true
;({ location: null }.hasOwnProperty("location")) // true
// Better I guess
!!({ location: undefined }).location // false

But on the other hand, if you expect a number, you will have weird failure on 0, which is very commonly a normal number. In which case you often check for undefined.

const fn1 = (num = 1) => num // How would we write this without default notation?
const fn2 = num => num || 1 // NO, YOU DIE!
const fn3 = num => (num === undefined ? 1 : num) // it's okay to not use typeof x === "undefined" in this context, it's a declared argument.

But it doesn't solve everything!

const window = { location: { hostname: { valueOf: () => "localhost" } } }
const hostname = typeof window !== "undefined" && window.location && window.location.hostname
""+hostname === "localhost" // The triple equals won't save you now, once string concatenation happened!

Maybe we should always use typeof :/
But what is your next action if hostname is an object? Pretending it wasn't set and defaulting to secure?

const needsSecure = () => {
  const hostname =
    typeof window === "object" &&
    typeof window.location === "object" &&
    typeof window.location.hostname === "string" &&
    window.location.hostname

  if ((hostname && hostname === "localhost") || hostname === "127.0.0.1")
    return false

  return true
}

Honestly, truthiness seems like the best bet to me, I just need to keep track of when it can be a 0 or "" or a literal significant false and it'll be okay.
I think I'll just keep using that.

> (undefined).potatoes
//TypeError: Cannot read property 'potatoes' of undefined
> (null).potatoes
//TypeError: Cannot read property 'potatoes' of null
> (true).potatoes
undefined // And it will never be anything truthy on a non-object, right? RIGHT?
> (true).valueOf
[Function: valueOf] // OH GOD DAMMIT!!