1

How to check if all of items are undefined or empty string ''?

var items = [variable_1, variable_2, variable_3];

Is there any nice way to do that instead of big if? Not ES6.

4
  • There's a .every() method on the Array prototype. (edited) Commented Jun 24, 2019 at 14:18
  • items.every(function(item) { return item === undefined || item === '' }) is ES5.1 -- or you could just check for falsey-ness (which includes null, empty strings, undefined, etc) !item Commented Jun 24, 2019 at 14:19
  • Actually, it's .every. .all is not standard JS, it's probably some library you've used Commented Jun 24, 2019 at 14:19
  • Use .every() or .filter() depending on what you want to do (test all values or only get the values that have some value you care about). Commented Jun 24, 2019 at 14:19

3 Answers 3

3

You can use every:

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

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

Comments

0

A one liner that uses Array.prototype.some to find at least one element which is not undefined or '', if it finds one it returns true

!items.some(item => item != undefined || item != '')

1 Comment

Consider using strict comparison, i.e. !==. Also, arrow functions are ES6. OP doesn't want ES6
0

Here's another one I just thought of:

if (array.join("") === "") 
  // all undefined or ""

Note that that'll also be true if an element is null, not undefined, so it may or may not suit the OP. Advantage is that it doesn't need a callback function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.