skip to Main Content

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


  1. 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)) {
      ...
    }
    
    Login or Signup to reply.
  2. 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!");
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search