2

This is simple beginner question - let suposse we have variable status:

var status = 'unknown';

and we want to grab error if:

if (status !== 'good' && status !== 'bad'){// error}

I wanted to shorten it to:

if (status !== 'good' && 'bad'){}

but it's not working? Is this even possible?

  • 2
    I don't think it is possible to shorten this in the way that you are thinking. You could use an array of conditions to achieve the same result. However, perhaps it is worth thinking about why you would want to shorten this perfectly fine, *easily readable* piece of code. – Ben Apr 15 '18 at 00:12
  • 1
    @Ben the way I did want to make the code looks like is more readable (I think so). If you have more statuses like warning/critical/non available etc. then status !== 'good' && 'bad' && 'warning' && 'critical' looks cleaner then repeating status !==. But the examples below are fine, and problem is solved. – glotfiovic1v Apr 15 '18 at 00:29
  • 1
    Sometimes being too fancy is detrimental to code readability. – Ivan Apr 15 '18 at 00:38
  • Possible duplicate of [Javascript: The prettiest way to compare one value against multiple values](https://stackoverflow.com/questions/9121395/javascript-the-prettiest-way-to-compare-one-value-against-multiple-values) – Sebastian Simon Apr 15 '18 at 01:14
  • Possible duplicate of [Check variable equality against a list of values](https://stackoverflow.com/questions/4728144/check-variable-equality-against-a-list-of-values) – rishat Apr 17 '18 at 20:38

3 Answers3

2

To make your code more DRY, you can make an array of conditions and then check to see if the string matches any of those conditions:

if (!['good', 'bad'].includes(status))

There isn't an operator shortcut like you're thinking of, though.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

You could use

if (!['good', 'bad'].includes(status)){}
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Benoît
  • 360
  • 2
  • 14
0

When using the if statement:

  if (status !== 'good' && 'bad'){}

JavaScript is trying to evaluate each side of the && separately. In your example status is 'unknown' so the left side (status !== 'good') will evaluate to true. Then the right side ('bad') will evaluate to true only because a non-empty string is a truthy value (https://developer.mozilla.org/en-US/docs/Glossary/Truthy). So any string (other than '') will evaluate to true and this has nothing to do with the code on the left of the &&.