2

I want to make my condition easier to read and wandering if it is possible to simplify this Scenario:

if((x === y)||(x === z)){...}
//and this one: 
x = (x === y) || (x === z)? ... : ...; 

//To something like: 
if(x === (y || z)){...}
x = x === (y || z) ?  ... : ...; 

This would get rid of the tons of brackets and variable duplication as well as "sounding" logical (at least for me): if this var x is this or that then I do this.

Especially when x is some long object reference e.g.:

this.someObject.KeyOfKeys[200].language === this.someOtherObject.KeyY.languages[10] || ...; 

Or how do you deal with logical "easy" but cumbersome to write conditions?

Pac0
  • 21,465
  • 8
  • 65
  • 74
telion
  • 834
  • 1
  • 9
  • 34
  • Yep, in operator won't work. I forgot it works on properties, not values. So, will work on (in case of arrays) indices, not values. – Adi B May 11 '20 at 06:36
  • 1
    Maybe it would be easier to outsource the comparison/assignment to a private function that does only that and has a good name describing what exactly you are trying to achieve? – jBuchholz May 11 '20 at 06:39
  • maybe this is the right place for you https://codereview.stackexchange.com/ – bill.gates May 11 '20 at 06:43
  • @Pac0 where does it say OP wants to get the value that was checked? I might have missed it. – adiga May 11 '20 at 06:57
  • @Pac0 ah, maybe. That is currently just assigning a boolean. telion, can you please clarify if you're trying to get the value that was successfully compared against OR do you just want to check if a value is included in a set of values? – adiga May 11 '20 at 07:02

1 Answers1

4

You can use includes() like so:

if ([y, z].includes(x)) { ... }
x = [y, z].includes(x) ? ... : ...;

As noted in the comments, this will not work with IE11 and older browsers.

Daniel Bank
  • 3,581
  • 3
  • 39
  • 50