1

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?

j08691
  • 204,283
  • 31
  • 260
  • 272
David Tunnell
  • 7,252
  • 20
  • 66
  • 124
  • 2
    () : () is not valid... Also 3 will never be reached. – Jonas Wilms May 24 '17 at 16:30
  • Change brackets? `(!contract.hasOwnProperty('COMMIT_CONTRACT')) ? '1' : (contract.hasOwnProperty('COMMIT_CONTRACT') ? '2' : '3')`? – Sayan Pal May 24 '17 at 16:32
  • Your second code is fine. Why do you need the first one ? a?1:(!a?2:"never reached") makes no sense to me... – Jonas Wilms May 24 '17 at 16:36
  • You can only chain them in the sense that if you have `e ? a : b` you can replace `a` or `b` with another `e ? a : b` However, even if the syntax you used were ok, there are only two possible outcomes here. –  May 24 '17 at 16:37
  • contract either has the property or it doesn't, there is no third condition – James May 24 '17 at 16:38

2 Answers2

4

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'.

Gaurav Gandhi
  • 3,041
  • 2
  • 27
  • 40
1

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';
Matt
  • 1,062
  • 1
  • 8
  • 11