1

I am just wondering, is there a way to assign a variable to the result of an if statement. Would something like this be allowed in javascript?

var result = if (someVariable === 2) { 
  return something; 
} else if (someOtherVariable) {
  return somethingElse;
} else { return null; }

Where result would end up being equal to whatever the if statement returns. Also, if this is not allowed in JS, is it allowed in other languages (just out of curiosity)?

applemonkey496
  • 683
  • 1
  • 10
  • 29
  • 1
    See use of a [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator), e.g., `var result = someVariable === 2 ? something : {something else, including potentially another ternary operation}; ` – sinaraheneba Aug 28 '19 at 23:23
  • Thanks @sinaraheneba! Is there a way to have it work for three options? – applemonkey496 Aug 28 '19 at 23:27
  • 1
    Yes, the false expression can include another ternary operation. Scroll down to 'conditional chains' on the linked page for an example. – sinaraheneba Aug 28 '19 at 23:28
  • 1
    That said, nested conditionals is pretty hard to read, it's generally not recommended. – Barmar Aug 28 '19 at 23:30

1 Answers1

2

Try using the ? operator.

var result = (someVariable === 2 ? something : (someOtherVariable ? somethingElse : null));

The operator works like this:

boolean ? result if true : result if false;

Aggs123
  • 171
  • 8