Home > Enterprise >  More elegant way to write returning if statement
More elegant way to write returning if statement

Time:07-10

I am trying to reduce the lines of code below, or even possibly use a ternary operator, but am having trouble getting the exact result.

let x = function(input) {
  if (input === 0) {
    return 0;
  } else if (input === 1) {
    return 1
  }
}
x(5)
x(1)
x(0)

CodePudding user response:

Return the input if the condition matches, and then you can combine the branches.

const x = (input) => {
  if (input === 0 || input === 1) {
    return input;
  }
};
console.log(x(5));
console.log(x(1));
console.log(x(0));

Or with the conditional operator and concise body

const x = (input) => input === 0 || input === 1 ? input : undefined;
console.log(x(5));
console.log(x(1));
console.log(x(0));

CodePudding user response:

If input is integer, you could use it as index of an array:

let x = input => [0,1][input];

console.log(x(5));
console.log(x(1));
console.log(x(0));

Or even key for object:

let x = input => ({0:0, 1:1, 11: "test"}[input]);

console.log(x(5));
console.log(x(1));
console.log(x(0));
console.log(x(11));

CodePudding user response:

Currently, your function returns undefined, 1, and 0 for those 3 invocations. If you want to do this with ternaries:

let x = function(input) {
  return input === 0 ? 0 : input === 1 ? 1 : undefined
}

This returns the same. Javascript ternaries. You can nest them, as seen above.

That being said, I like CertainPerformance's answer better.

  • Related