10
votes

Why is it that when I do

(!true) ? 'false' : 'true'

it returns 'true'?

8
FYI, if you're happen to want the string 'true' or 'false' from a variable, you can also type: !var+'' (or !!var+'' if you want it flipped)Nobody
What did you expect it to return?Corneliu
Why hasn't this question contains an accepted answer?Buhake Sindi
@Buhake, maybe JM at Work was confused by the opening parenthesis without a closing one and did not want to accept?Amelse Etomer
@Sebastian Langer, Aaah! Well spotted, 2 years after posting the original answer! Thanks! :-)Buhake Sindi

8 Answers

65
votes

It simply means

if (!true) {
  return 'false';
} else {
  return 'true';
}

!true (not true) means false, so the else is returned.

23
votes

The syntax of A ? B : C means that if A is TRUE, then return the value B. Else return value C. Since A is FALSE, it returns the value C which happens to be true.

21
votes

Because (!true) is false, and then the right side of the : is chosen.

17
votes

Because the above is equivalent to:

if (false) {
    return 'false';
} else {
    return 'true';
}

Though perhaps the confusion is coming from the difference between:

if (false) // which is false

And

if (false == false) // which is true
7
votes

This can be expanded to:

if(!true){
   return 'false';
} else {
   return 'true';
}
1
votes

The confusion lies here because of the use of string literals to represent boolean values. If you reverse the 'false' and 'true', it makes more sense:

(!true) ? 'true' : 'false'

Would return the string literal false, which is much different than a boolean value.

Your original statement (!true) ? 'false' : 'true' reads as

"If not true, then return the string literal true".

The statement I posted first reads as

"If not true, then return the string literal false".

Which, if you know the opposite (not) value of true is false, then it explains the logic illustrated.

1
votes

if(!true) is equivalent to if(!true= true) which is equivalent to if(false=true) which is false. Therefore return (true) which is on the false side of the if statement.

0
votes

const test = true; // change this value to see the result change  
 
 if (!test) { // if test is NOT truthy
     console.log('false')
 } else { // if test === true
     console.log('true')
 }
// Since in the original question a ternary expression was used, the above code is equivalent to this:

!test ? console.log('false') : console.log('true');