1

So, I just want to ask, is it some more beautify way to write such conditions:

state === 'su' || state === 'ja' || state === 'fa'

I mean, maybe they can be rewrited like:

state === ('su' || 'ja' || 'fa')

Thanks

Max Wolfen
  • 1,923
  • 6
  • 24
  • 42
  • The two pieces of code are not equivalent the slightest. In the first case you check if `state` is `su` or `ja` or `fa`, while the second is essentially `state === "su"` – VLAZ May 23 '18 at 18:27
  • 6
    `['su','ja','fa'].includes( state )` – Paul May 23 '18 at 18:27
  • 1
    @Paulpro [Not supported](https://caniuse.com/#search=includes) in IE though. Use `['su', 'ja', 'fa'].indexOf(state) >= 0` for a more portable solution. – Thomas May 23 '18 at 18:31
  • 1
    @Thomas There are tons of language features and web standards that aren't supported by IE or Edge. IMO it's better to just use the features and add polyfills if you need to support those browsers. – Paul May 23 '18 at 18:34
  • 1
    Possible duplicate of [Check variable equality against a list of values](https://stackoverflow.com/questions/4728144/check-variable-equality-against-a-list-of-values) – Heretic Monkey May 23 '18 at 18:34

4 Answers4

1

As @Paulpro stated in his comment. You can use

['su','ja','fa'].includes( state ).

I am adding it as an answer, so It'd be useful for someone sometime and easy to find.

Muhammad Usman
  • 10,039
  • 22
  • 39
1

As said by @Paulpro - you can really easy check a lot of incoming value by array method includes. So, we can make it in more beauty way as you want.

see for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Sviat Kuzhelev
  • 1,758
  • 10
  • 28
1

You can use the indexOf() method that arrays have, e.g.

['su', 'ja', 'fa'].indexOf('ja') > -1; // true

For maximum beauty, have your aray declared as a variable first, e.g.

valid = ['su', 'ja', 'fa', 'la', 'ti', 'do'];
valid.indexOf(state) > -1;

This way, your code looks tidy even if the list of valid values is long.

See more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

0

I think that you should write (state === 'su' || state === 'ja' || state === 'fa').

It's simpler that way for other programmer to understand.

Liam Newmarch
  • 3,935
  • 3
  • 32
  • 46