Why is it that when I do
(!true) ? 'false' : 'true'
it returns 'true'
?
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');
!var+''
(or!!var+''
if you want it flipped) – Nobody