Javien
Javien

Reputation: 188

What's the best way to figure out 'undefined' in several variables?

When there are several variables and figure out even one of them is undefined, which code is the best one?

variable is like below

const [a, b, c] = [1, '4', undefined]
  1. use Array.includes
[a, b, c].map(e => typeof e).includes('undefined')
  1. use for ... of
for (const e of [a, b, c]) {
    if (typeof e === 'undefined') {
        // 'undefined' found
    }
}

Upvotes: 0

Views: 79

Answers (4)

muriukialex
muriukialex

Reputation: 93

 const array = [1, '4', undefined];
 const isOneOfThemIsUndefined = array.filter(Boolean)

 console.log(isOneOfThemIsUndefined)

// =>  [1, '4',]

Upvotes: 0

mrtechtroid
mrtechtroid

Reputation: 708

You can also use without typeOf as if (e === undefined) in for loop Now coming back to your question. As described in this answer it depends on your use scenario.
If the majorly of the arrays are reasonably small then you can use either. But if they are extremely large, a for loop is preferable as it's much faster than .map()

Upvotes: -1

Bergi
Bergi

Reputation: 664434

A simple includes call will do, without the typeof mapping:

[a, b, c].includes(undefined)

Upvotes: 1

Oleksii Nuzhyn
Oleksii Nuzhyn

Reputation: 91

It depends on what you mean under "the best code". If you care about readability, you should choose the functional way.

even one of them is undefined

According to the description, the method you are looking for is some. Also, it's better to check for undefined explicitly, preferring the typeof operator

const array = [1, '4', undefined];

const isOneOfThemIsUndefined = array.some(e => typeof e === 'undefined'))

Upvotes: 2

Related Questions