nandesuka
nandesuka

Reputation: 799

Conditional return (no if or ternary)

I thought this would be very simple but I am unable to think of a way to conditionally return without using an if or ternary.

const example = (num1, num2) => {
  num1 === num2 && return 'equal';
  num1 !== num2 && return 'not equal';
}

This gives me an error saying Unexpected token return.

Upvotes: 2

Views: 140

Answers (2)

Samuel
Samuel

Reputation: 1421

const example = (num1, num2) => num1 === num2 && 'equal' || 'not equal'
const example = (num1, num2) => ['equal', 'not equal'][+(num1 !== num2)]

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370689

If you had to avoid both the conditional operator and if statements, you could abuse && and || to get to the logic you need, by prepending a 'not ' onto the 'equal' returned if needed:

const example = (num1, num2) => (
  ((num1 !== num2 && 'not ') || '') + 'equal'
);

console.log(example(2, 3));
console.log(example(3, 3));

Upvotes: 3

Related Questions