Search code examples
javascriptlogic

How can I implement logics without if else, switch or a built-in function in javascript


Suppose we have function, which returns 3 when passing 5 to it and return 5 when passing 3 to it. I know it is very easy with if else and switch.

for example

function countReturn(number){
  if(number === 3){
  return 5
 }

  if(number === 5){
  return 3
 }

}

But how can I implement the same logic without if else, switch or any built-in function?


Solution

  • You can store the return values in an array:

    function countReturn(n) {
      let a = [,,,5,,3];
      return a[n];
    }
    

    That will return undefined for other inputs, just like your original code.