Truthy vs Falsy values in JavaScript
When you write if/else statement in any programming language, you expect to pass a value in the if() condition that is strictly boolean which means either true or false. It could also be an expression that evaluates to one of these values as demonstrated below.
However, JavaScript goes beyond that. In JavaScript,
if/else statement checks if a value is truthy or falsy. A truthy value is like true and a falsy value is like false. These are as follows.falsy -> false, '', "", 0, -0, 0n, NaN, null, undefined
truthy -> anything that is not mentioned above
truthy -> anything that is not mentioned above
You can convert a truthy and falsy value to a corresponding native boolean value. There are two ways to do that. Ether you can use logical NOT operator (!) or you can use
Boolean constructor as a function.When Boolean function is executed with a truthy value, it returns true else it returns false which could be useful in some operations such as filter.
Comments
Post a Comment