Vadzim Savenok Vadzim Savenok - 1 month ago 7
Javascript Question

How to check if only one value is not null in Javascript?

Let's say I have 3 textboxes in cshtml. What I am trying to do in Javascript is the following:

Check if ANY OF those 3 values and ONLY THEM is not null.

The only way I can think of is doing it manually:

if ((val1 & !val2 & !val3) || (!val1 & val2 & !val3) || (!val1 & !val2 & val3))


It is okay if it is a small number of textboxes, but if such number grows to 10+, it might become a hassle.

Is there any efficient way to implement such logic in Javascript regardless of how many textboxes we are dealing with?

Answer

You can use .reduce:

var nonEmpty = [val1, val2, val3].reduce(((c, v) => c += (v !== "")), 0);
if (nonEmpty === 1) {
  // exactly one is not empty
}

Any other way of counting the non-empty inputs and checking that the count is equal to 1 would work too of course.

What that .reduce() code does is use an "arrow function" that increments a counter (c) when a value is not the empty string. (If you want to check for null, you can do that instead of course.) You could use a plain old-fashioned function too:

var nonEmpty = [val1, val2, val3].reduce(function(c, v) {
  return c += (v !== "");
}, 0);

The .reduce() function is passed 2 parameters: that callback function, and the initial value of c (zero in this case). The return value will be the final value of c returned by the last call to the callback.