Why is it that when I do
(!true) ? 'false' : 'true'
it returns 'true'
?
Why is it that when I do
(!true) ? 'false' : 'true'
it returns 'true'
?
It simply means
if (!true) {
return 'false';
} else {
return 'true';
}
!true
(not true) means false
, so the else
is returned.
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
.
Because (!true)
is false, and then the right side of the :
is chosen.
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
This can be expanded to:
if(!true){
return 'false';
} else {
return 'true';
}
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.
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.
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');