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)?

4
  • 1
    See use of a ternary operator, e.g., var result = someVariable === 2 ? something : {something else, including potentially another ternary operation}; Commented Aug 28, 2019 at 23:23
  • Thanks @sinaraheneba! Is there a way to have it work for three options? Commented Aug 28, 2019 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. Commented Aug 28, 2019 at 23:28
  • 1
    That said, nested conditionals is pretty hard to read, it's generally not recommended. Commented Aug 28, 2019 at 23:30

1 Answer 1

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;

Sign up to request clarification or add additional context in comments.

1 Comment

Just cleaning up some old posts, and I realised I hadn't accepted this answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.