When a value is truthy in Javascript, it does not means that the value is equal to true but it means that the value coerces to true when evaluated in a boolean context.
falsy -> false, '', "", 0, -0, 0n, NaN, null, undefined
truthy -> anything that is not mentioned above
When a value is truthy in Javascript, it does not means that the value is equal to true but it means that the value coerces to true when evaluated in a boolean context.
function truthyOrFalsy(value){
if(value){
console.log("Truthy Value");
} else {
console.log("Falsy Value");
}
}
The above function evaluates the passed value in a Boolean Context(if condition) and checks if whether the passed value is truthy or falsy.
Most of the values in javascript are Truthy, so it is better to list the Falsy value where we have only a limited number of cases. There are atotal of 8 falsy values in Javascript:
We can validate whether the above values are falsy or not by passing them as a parameter to the truthyOrFalsy function we defined at the starting of this article.
truthyOrFalsy(undefined); // Falsy Value
truthyOrFalsy(NaN); // Falsy Value
truthyOrFalsy(null) // Falsy Value
truthyOrFalsy(""); // Falsy Value
truthyOrFalsy(false) // Falsy Value
truthyOrFalsy(0); // Falsy Value
truthyOrFalsy(-0); // Falsy Value
truthyOrFalsy(0n); // Falsy Value