0

I'm trying to debug someone`s code. The "e" variable line is checking whether the user has "save-data" enabled or if he's on a slow (2g) connection.

e = navigator.connection && (navigator.connection.saveData || (navigator.connection.effectiveType || "").includes("2g"));
    if (!e && d)...

The part I'm confused about is the empty brackets in the last OR statement. Is it just a redundant code or am I missing something?

What's the point for checking whether an empty string has "2g" in it?

Serge
  • 3
  • 3
  • It's a fallback, so if everything else's `undefined` or `null`, it will safely return `false` instead of throwing an error. – FZs Feb 15 '21 at 15:36
  • `a || b || c` will give you *either* the first truthy value *or* the last falsy value. If all of these are, for example, `null`, then you'll get `null`. If you try `(a || b || c).includes("whatever")` you'll get an error. If you want to protect against this, then you add an empty string and you're sure that if all are falsy non-string values, you at least have a fallback. – VLAZ Feb 15 '21 at 15:37

1 Answers1

1

(navigator.connection.effectiveType || "") will resolve to an empty string if effectiveType is null, undefined or some other falsy non-string value.

If you didn't do that you'd attempt to call null.includes() which would throw an exception.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335