0

I am wondering if grouping values with || while comparing a single variable value is considered valid in the latest JavaScript or TypeScript and if not, does anyone know a reason for this to not become valid syntactic sugar at some point? Or if it is allowed, in what version of JS was this added and what is this type of shortcut comparison called?

const exampleVar: 'a' | 'b' | 'c' | 'd' = 'a'

// I want to see if example var is 'a' or 'b'
if ( exampleVar === ( 'a' || 'b') ) {
  console.log('Yay!');
} else {
  console.log("Not 'a' or 'b' - Boo!");
}

I would expect this to return true if exampleVar is 'a' or 'b'. It works in console in an evergreen browser so I think my two biggest questions are where can this be safely used and what is this shortcut called so I can check its support in something like CanIUse.

3
  • 3
    The syntax is legal, it just doesn't do what you want. Order of operations says to evaluate 'a' || 'b' first, which just results in 'a'. So the code is equivalent to if (exampleVar === 'a'). Commented Jan 14, 2024 at 2:22
  • "I would expect this to return true if exampleVar is 'a' or 'b'. It works in console in an evergreen browser", I think you might want to check that again. If you try with exampleVar set to 'b' you'll get the else branch log. (unless when you say "it works" you mean that it doesn't crash?) Commented Jan 14, 2024 at 2:24
  • 1
    @NickParsons You are correct. I only tested for the 'a' condition. After trying again, it failed as you describe. Thanks for the clarification. Commented Jan 16, 2024 at 3:59

2 Answers 2

4

No, that doesn't work like you think it does.

exampleVar === ( 'a' || 'b') is equivalent to exampleVar === 'a'

The or operator, return the right hand value if the left hand is falsy.

The closest to what you are looking for is probably :

if(['a', 'b'].includes(exempleVar)) {
  ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Matthieu! Great answer with both an explanation of the issue as well as a great solution for my use case.
0

You can use switch:

switch(exampleVar) {
case 'a':
case 'b':
  console.log('Yay!');
  break;
case 'c':
  console.log('Yay again!');
  break;
default:
  console.log("Not 'a' or 'b' or 'c' - Boo!");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.