Skip to content Skip to sidebar Skip to footer

Javascript Falsy Values (null, Undefined, False, Empty String: "" Or '' And 0) And Comparison(==) Operator

When I am using any one of values(null, undefined, false, '', 0) in a if statement, it is always evaluated as fallacy(false). Also, the negation of these values((null, undefined, f

Solution 1:

A common misconception

"...If double equalto (==) operator only checks/compares for values & not for types..."

That's an incorrect assumption, though it's often repeated by people. In reality, the ==does check types, and in fact pays far more attention to the types than a === comparison does.

See Abstract Equality Comparison Algorithm.

A == comparison doesn't do a simple toBoolean conversion. Rather it walks through a somewhat complex recursive algorithm, which, after checking the types, attempts to coerce the operands to the same type if they don't match.

The type coercion that it performs is very specific to the types of the operands. A different sequence of coercions can take place for different type pairs. Usually (but not always) it ends up ultimately coercing the operands down to number types.


Why !ing the operands changes things

When you manually coerce both operands using !, you're now doing a simple toBoolean conversion causing the types to match, which avoids the type coercive part of the algorithm, making it behave essentially like the Strict Equality Comparison Algorithm.

So the only way to predict the outcome of a == comparison when the types don't match is to understand that Abstract algorithm.


Don't forget about NaN

And FYI, there's one more "falsey" value to consider, NaN. Its == comparison will always be false, no matter what. Even when comparing to another NaN value, it'll be false.

Solution 2:

undefined: means a variable was declared but has no value assigned

null: the value of null has been assigned, which means it has no value

false, '' and 0 I think you can probably work out what these mean.

Solution 3:

NULL is different from false (NULL is of type object and false is of type of boolean), null is different from 0 (0 is of type integer), null is also different from '' ('' is of type of string). but they are all falsy values. The ! operator negates a boolean value. If ! is used on falsy values, it results to conversion of falsy values to an object of type boolean.

Post a Comment for "Javascript Falsy Values (null, Undefined, False, Empty String: "" Or '' And 0) And Comparison(==) Operator"