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.
2
Answers
No, that doesn’t work like you think it does.
exampleVar === ( 'a' || 'b')
is equivalent toexampleVar === '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 :
You can use switch: