I thought I knew about the quirks with ==
and all the strange type casts in JavaScript, but today I stumbled upon one thing that doesn't make any sense to me:
'\t' == false // => true
Why is that?
Apparently, '\t'
is not a falsy value, and if combined with ||
it works as excpected:
'\t' || 42 // => '\t'
On the other hand, a toString
is also not called on false
, see:
'\t' == 'false' // => false
This led me to thinking that the tab maybe gets converted to a boolean, but:
Boolean('\t') == false // => false
So, the question is: Why is that?
Alternative expression Because [] creates a new array, so you are comparing one array object with another array object. It's not the contents of the arrays that is compared, the object references are compared. They are not equal because it's not the same object instance.
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.
Note that === never causes type coercion, but checks for correct types first and yields false if they are not equal!
A falsy (sometimes written falsey) value is a value that is considered false when encountered in a Boolean context. JavaScript uses type conversion to coerce any value to a Boolean in contexts that require it, such as conditionals and loops. The keyword false .
See Abstract Equality Comparison::
The comparison
x == y
, where x and y are values, produces true or false. Such a comparison is performed as follows:
So, in your situation, x
is a string, and y
is a boolean. The first condition that is fulfilled here is:
- If Type(y) is Boolean, return the result of the comparison
x == ToNumber(y)
.
Turning the check into
'\t' == 0
Which then fulfills:
- If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
And ToNumber('\t') === 0
:
console.log(Number('\t'));
Turning the check into
0 == 0
which is the same as
0 === 0
or true
.
Note that while a string composed of all whitespace is == false
, calling Boolean on such a string will return true
, because the string has a non-zero length:
console.log( Boolean(' '), Boolean('\t') );
Of course, it would be best to always avoid ==
- use ===
instead, and you won't have to worry about these silly coercion rules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With