David Tunnell
David Tunnell

Reputation: 7532

Nesting ternary operators

I am trying to write a long if else if

(!contract.hasOwnProperty('COMMIT_CONTRACT') ? '1') : (contract.hasOwnProperty('COMMIT_CONTRACT') ? '2' : '3')

However, this is failing to evaluate.

I started with:

(!contract.hasOwnProperty('COMMIT_CONTRACT')) ? '1' : '2')

But according to here you can chain them: javascript shorthand if statement, without the else portion

But it's not evaluating correctly. What am I doing wrong and how do I fix it?

Upvotes: 1

Views: 3456

Answers (2)

Matt
Matt

Reputation: 1082

You don't need all the () around everything. This will work just fine:

var variable = !contract.hasOwnProperty('COMMIT_CONTRACT') ? '1' : contract.hasOwnProperty('COMMIT_CONTRACT') ? '2' : '3';

Upvotes: 1

Gaurav Gandhi
Gaurav Gandhi

Reputation: 3201

You messed up with parenthesis (()).

According to my understanding,
This is your first condition: !contract.hasOwnProperty('COMMIT_CONTRACT'),
Your if part of first condition is '1',
Your else part of first condition is second condition: contract.hasOwnProperty('COMMIT_CONTRACT'),
Your if part of second condition is '2',
Your else part of second condition is '3'.

Let's add some parenthesis to make it more readable by us as well to compilers,

( !contract.hasOwnProperty('COMMIT_CONTRACT') ) ? '1' : ( contract.hasOwnProperty('COMMIT_CONTRACT') ? '2' : '3' )

Fun Fact, You will never get '3'.

Upvotes: 4

Related Questions