In the below code :
console.log( (false || “test”) ? “first” : “second”) );
The o/p of first part is test ( false || “test”) , so how is my final o/p first ? What happens in general when the conditional operator can’t evaluate an expression as True or False ?
Every value in javascript, regardless of its type, can be coerced to a boolean value.
Values that coerce to
falseare called “falsey”, and values that coerce totrueare called “truthy”.Here’s a fiddle demonstrating this coercion.
In this case:
(false || "test")is logically equivalent to("test")sincefalse || Xis equivalent toX(this is called a disjunctive syllogism, if you’re interested in logics).Any non-empty string in javascript (including the string
'false', have fun with that bug) coerces totrue, so the tertiary condition evaluates totrueand logs'first'.