JM at Work
JM at Work

Reputation: 2437

Why is !true ? 'false' : 'true' returning 'true'?

Why is it that when I do

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

it returns 'true'?

Upvotes: 10

Views: 86133

Answers (8)

Dženis H.
Dženis H.

Reputation: 7822

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');

Upvotes: 0

StKiller
StKiller

Reputation: 7951

This can be expanded to:

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

Upvotes: 7

Buhake Sindi
Buhake Sindi

Reputation: 89209

It simply means

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

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

Upvotes: 67

ndabenhle
ndabenhle

Reputation: 35

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.

Upvotes: 1

user2591612
user2591612

Reputation:

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.

Upvotes: 1

Daniel
Daniel

Reputation: 28104

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

Upvotes: 21

user684934
user684934

Reputation:

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.

Upvotes: 23

David Tang
David Tang

Reputation: 93714

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

Upvotes: 17

Related Questions