-1

Suppose I have several environment variables, going by the hypothetical names OBJECT_A, OBJECT_B, OBJECT_C, etc. I must implement a function doTheyExist() that must return a boolean. I want to know what is the cleanest (as in, as little code as possible and as easy to read as possible) and the most efficient (as in using as few resources as possible) to implement such a function.

function doTheyExist() {
    if (
        process.env.OBJECT_A &&
        process.env.OBJECT_B &&
        process.env.OBJECT_C &&
        ...
    ) return true;
    return false;
}

I initially thought I could just use a return (object_a && object_b && ...); would be the way to go, as it saves a line, but turns out it might return an undefined, rather than a false. I cannot have that. The return must be strictly true or false. Is there any cleaner way of doing this? And I know this is a minor thing and won't affect overall performance even if I were to check for thousands of variables, but is this the most efficient way of making checks like these?

4
  • [...].every(Boolean), maybe? Commented Mar 21, 2024 at 13:44
  • "but turns out it might return an undefined, rather than a false" it would have never returned a boolean anyway. Only a truthy or falsy value Commented Mar 21, 2024 at 13:44
  • Boolean(object_a && object_b &&...) or use ternary object_a && object_b &&... ? true : false Commented Mar 21, 2024 at 13:45
  • Protip: !undefined is true. !!undefined is false. Commented Mar 21, 2024 at 13:46

1 Answer 1

0

You could define an array of keys you want to check, then using every() you can check if the object hasOwnProperty for all the keys.

const data = {
    OBJECT_A: 1,
    OBJECT_B: 2,
    OBJECT_C: 3
};

const objectHasKeys = (obj, keys) => keys.every(k => data.hasOwnProperty(k));

console.log(objectHasKeys(data, [ 'OBJECT_A' ]));
console.log(objectHasKeys(data, [ 'OBJECT_A', 'OBJECT_B' ]));
console.log(objectHasKeys(data, [ 'OBJECT_X', 'OBJECT_Y' ]));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.