Predict the output of the following javascript code
console.log(false == '0');
Quiz Explanation
In JavaScript, when you use the loose equality operator (==
), it performs type coercion if the operands are of different types. Type coercion means converting the operands to a common type before comparison.
In this expression, false
is a boolean value, and '0'
is a string.
During the comparison, JavaScript coerces the operands to a common type. In this case, it converts the boolean value false
to a number, which becomes 0
. Then it compares 0
(from false
) with the string '0'
.
After coercion, both sides are 0
, so the comparison becomes 0 == '0'
.
Now, JavaScript further coerces the string '0'
to a number because one operand is a number. So, '0'
is converted to 0
.
After coercion, the comparison becomes 0 == 0
.
Since both sides are now of the same type (number) and have the same value (0
), the comparison evaluates to true
.
Therefore, the output of the given code will be:
true