Crocsx
Crocsx

Reputation: 7640

ternary operation in js

Maybe I do not understand ternary operation but

if I am right it's

    test ? true : false

So this should give

function toto(x, y)
{ 
    return (x > 0 ? x < 7 ? true : false : false &&
                y > 0 ? y < 6 ? true : false : false)
}

true only if 0

but if I do

toto(4,6)

it returns true, why? What am I missing ?

Upvotes: 0

Views: 97

Answers (4)

Mesar ali
Mesar ali

Reputation: 1898

Operator precedence affecting it here

function toto(x, y)
{ 
return ((x > 0 ? x < 7 ? true : false : false) && (y > 0 ? y < 6 ? true : false : false)) 
}

Upvotes: 0

Crocsx
Crocsx

Reputation: 7640

just do like this :

function toto(x, y)
{ 
    return (x > 0 ? x < 7 ? true : false : false ) &&
                ( y > 0 ? y < 6 ? true : false : false)
}

with the bracket before and after the exp1 and exp2 and yes it's a bit unreadable ^^

edit : I also would do

return (x > 0 && x < 7) && (y > 0 && y < 6)

Upvotes: 0

Ludovit Mydla
Ludovit Mydla

Reputation: 822

Aren't you trying to achieve this? chceking whether the x is from 0..7 and y is 0..6?

function toto(x, y)
{ 
return (x > 0 && x < 7) && (y > 0 && y < 6 );
}

Upvotes: 0

xianshenglu
xianshenglu

Reputation: 5369

you need eslint to format your code ,this is the formatted code,see:

function toto(x, y) {
  return x > 0
    ? x < 7
      ? true
      : false
    : false && y > 0
      ? y < 6
        ? true
        : false
      : false
}

image:

enter image description here I think ,it is easier to understand

Upvotes: 0

Related Questions