Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is tab equal to false in JavaScript? [duplicate]

Tags:

javascript

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?

like image 966
Golo Roden Avatar asked Aug 06 '19 09:08

Golo Roden


People also ask

Why [] == [] is false in JavaScript?

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.

Why True == true is false in JS?

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.

Does === return false?

Note that === never causes type coercion, but checks for correct types first and yields false if they are not equal!

Is false false in JavaScript?

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 .


1 Answers

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:

  1. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

Turning the check into

'\t' == 0 

Which then fulfills:

  1. 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.

like image 160
CertainPerformance Avatar answered Sep 21 '22 02:09

CertainPerformance