Truthy / Falsy
In JavaScript, a truthy or falsy value is a value that is being casted into a boolean when evaluated in a boolean context. An example of boolean context would be the evaluation of an if condition:
Every value will be casted to true unless they are equal to:
false0""(empty string)nullundefinedNaN
Here are examples of boolean context:
ifcondition evaluation
myVar can be any first-class citizen (variable, function, boolean) but it will be casted into a boolean because it's evaluated in a boolean context.
- After logical NOT
!operator
This operator returns false if its single operand can be converted to true; otherwise, returns true.
- With the Boolean object constructor
- In a ternary evaluation
myVar is evaluated in a boolean context.
Be careful when comparing 2 values. The object values (that should be cast to true) is not being casted to Boolean but it forced to convert into a primitive value one using ToPrimitives specification. Internally, when an object is compared to Boolean value like [] == true, it does [].toString() == true so...