Search code examples
javascriptfunctionlogic

Is there a way to shorten multiple || (or) in a single function?


I have this function. It works fine. Is there a way to shorten the logic though?

function doNotDuplicateRandomIndex() {
  if (randomIndex === 0 || randomIndex === 1 || randomIndex === 2 || randomIndex ===3) {
    createRandomIndex();
  }
}

I haven't tried anything else, simply because I don't know where to start.


Solution

  • Use the Less than (<) operator. You're welcome.

    function doNotDuplicateRandomIndex() {
      if (randomIndex < 4) {
        createRandomIndex();
      }
    }
    

    In fact, this can be even shorter by removing the brackets from the if...else statement.

    See: Are braces necessary in one-line statements in JavaScript?

    function doNotDuplicateRandomIndex() {
      if (randomIndex < 4) createRandomIndex();
    }
    

    Insane, we can make the whole function even shorter by converting it to an arrow function expression.

    The if...else statement is replaced with a Logical AND (&&) operator.

    const doNotDuplicateRandomIndex = () => randomIndex < 4 && createRandomIndex();
    

    Nice answer by XMehdi01, the same concept can be converted to an arrow function expression too.

    const doNotDuplicateRandomIndex = () => [0, 1, 2, 3].includes(randomIndex) && createRandomIndex();