Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `'\t\n ' == false` in JavaScript?

In JavaScript...

'\t\n ' == false // true

I can assume that any string that consists solely of whitespace characters is considered equal to false in JavaScript.

According to this article, I figured that false would be converted to 0, but was unable to find mention of whitespace considered equal to false using Google.

Why is this? Is there some good reading on the subject besides digging into the ECMAScript spec?

like image 437
alex Avatar asked Apr 12 '11 11:04

alex


People also ask

Why == is false in JavaScript?

Because == (and === ) test to see if two objects are the same object and not if they are identical objects.

Why is false == false is false in JavaScript?

The answer is because "false" is a string (as Gerardo Furado pointed out in the comments), the test you are making is equivalent to false = "hello". Javascript does not look at the word in the string to determine if it is a boolean and then try to get the value from that.

Why is the result of === false?

The '==' operator tests for abstract equality i.e. it does the necessary type conversions before doing the equality comparison. But the '===' operator tests for strict equality i.e it will not do the type conversion hence if the two values are not of the same type, when compared, it will return false.

Why do false == [] and false == ![] Both return true?

Types of x and y are checked when x == y is to be checked. If no rule matches, a false is returned. For [] == true , rule 7 matches, so a result of [] == ToNumber(true) is returned i.e. false is returned. Reason you're getting the same result for ![]


1 Answers

This page provides a good summary of the rules.

Going by those rules, the '\t\n ' is converted in a number (Number('\t\n') ==> 0), and the false is converted into a number (Number(false) ==> 0), and hence the two are equal.


Alex's answer is also a good breakdown of the particular case of '\t\n ' == false.


An important distinction is that '\t\n ' is not falsy. For example:

if ('\t\n ') alert('not falsy'); // will produce the alert
like image 91
David Tang Avatar answered Oct 25 '22 22:10

David Tang