Reputation: 31
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?
Upvotes: 2
Views: 588
Reputation: 1
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 &&.
Upvotes: 0
Reputation: 371009
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.
Upvotes: 2