Ad

Is It Possible To Use A Shorter Helper Function Instead Of Typeof Something !== "undefined"?

- 1 answer

This works fine

var isRenderer = typeof process !== "undefined" && process.type === "renderer";

I don't like having those typeof checks all over my code, so I tried writing a helper function. But using it causes a reference error to be thrown

var isRenderer = !isUndefined(process) && process.type === "renderer";

function isUndefined(val) {
  return typeof val === "undefined";
}

I have two questions:

  • Why does the helper function I wrote not work?
  • Is it possible to write a helper function to replace the typeof checks?
Ad

Answer

I don't like having those typeof checks all over my code, so I tried writing a helper function. But using it causes a reference error to be thrown

If you got an error with your function, that tells us that process is an undeclared identifier, not just a variable/parameter whose value is undefined. You can use typeof on an undeclared identifier, but you can't read its value.

Unfortunately, you can't write a function to do what you've outlined. The closest you can come is:

var isRenderer = !isUndefined(typeof process) && process.type === "renderer";

function isUndefined(type) {
  return type === "undefined";
}

Note that it still needs typeof at the point where you're calling it. But at least it avoids the opportunity of a silent logic error if you had a typo in "undefined" (as I often do).

The best course is to look at the reasons you would be trying to use an undeclared identifier and address those. But barring doing that, you'll need the typeof check.


If process were a declared identifier but it had the value undefined, your function would have worked. But in that scenario, you soon wouldn't need it because of optional chaining. That's a new feature in the ES2020 specification that's in modern JavaScript environments (Chrome v80+, Firefox v74+, Safari 13.1+) and can be used with older JavaScript environments if you transpile (for instance, with Babel). Then your statement would look like this:

// ONLY WORKS IF `process` IS DECLARED
var isRenderer = process?.type === "renderer";

isRenderer would be false if process were declared but had the value undefined or null, because process?.type would evaluate to undefined, and undefined === "renderer" is false.

But again, that won't work in the situation you have, since process is an undeclared identifier.

Ad
source: stackoverflow.com
Ad