0

I'm trying to use the logical operator && in my ternary operator while chaining and it isn't working... For example:

(x === 5 && y === 5) ? (do something) 
: (x === 5 && y === 4) ? (do something else) 
: (x === 5 && y === 3) ? (do a third thing) 
: null

Is this possible? Is there another way to do this?

Dee
  • 11

3 Answers3

3
x === 5 ? 
  y === 5 ? console.log('x=5, y=5') :
  y === 4 ? console.log('x=5, y=4') :
  y === 3 ? console.log('x=5, y=3') : null
: null

proof:

const resp = (x,y) => x === 5 ? 
                        y === 5 ? 'x==5, y==5' :
                        y === 4 ? 'x==5, y==4' :
                        y === 3 ? 'x==5, y==3' : 'x==5, y==?'
                      : 'x==?, y==?'

console.log ( '1 ,2 ', resp(1,2) )  // 1 ,2  x==?, y==?
console.log ( '5 ,2 ', resp(5,2) )  // 5 ,2  x==5, y==? 
console.log ( '5 ,4 ', resp(5,4) )  // 5 ,4  x==5, y==4
Mister Jojo
  • 12,060
  • 3
  • 14
  • 33
rajjix
  • 161
  • 5
1

yes You can do your way :

const Question = (x,y) => (x === 5 && y === 5) ?  'x==5, y==5' 
                        : (x === 5 && y === 4) ?  'x==5, y==4' 
                        : (x === 5 && y === 3) ?  'x==5, y==3' 
                        : 'x==?, y==?' 

console.log ( '1 ,2 ', Question(1,2) )  // 1 ,2  x==?, y==?
console.log ( '5 ,2 ', Question(5,2) )  // 5 ,2  x==?, y==? 
console.log ( '5 ,4 ', Question(5,4) )  // 5 ,4  x==5, y==4
Mister Jojo
  • 12,060
  • 3
  • 14
  • 33
0

Use parentheses to specify nested conditions for success and failure.

    (x === 5 && y === 5) ? (do something) : ((x === 5 && y === 4) ? (do something
      else) : ((x === 5 && y === 3) ? (do a third thing) : null));

proof:

const test = (x,y) => (x === 5 && y === 5) 
                      ? 'x==5, y==5' 
                      : ( (x === 5 && y === 4) 
                          ? 'x==5, y==4' 
                          : ( (x === 5 && y === 3) 
                              ? 'x==5, y==5'
                              : 'x==?, y==?'
                        )   );

console.log ( '1 ,2 ', test(1,2) )  // 1 ,2  x==?, y==?
console.log ( '5 ,2 ', test(5,2) )  // 5 ,2  x==?, y==? 
console.log ( '5 ,4 ', test(5,4) )  // 5 ,4  x==5, y==4
Mister Jojo
  • 12,060
  • 3
  • 14
  • 33
Akshay Bande
  • 2,064
  • 2
  • 6
  • 19