Today when I was doing some experiments with ==, I accidentally found out that "\n\t\r" == 0. How on earth does "\n\t\r" equal to 0, or false?
What I did is:
var txt = "\n"; //new line
txt == 0; //it gives me true
And that really annoy me. So I did more:
var txt = "\r"; //"return"
txt == 0; //true
var txt = "\t"; //"tab"
txt == 0; //true
It does not make sense, at all. How’s that happen? And more crazy is this:
//Checking for variable declared or not
var txt ="\n\t\r";
if(txt!=false){
console.log("Variable is declared.");
}else{
console.log("Variable is not declared.");
}
What it gives me is Variable is not declared.
How is it equal to 0, or false???
This behaviour might be surprising but can be explained by having a look at the specification.
We have to look at the what happens when a comparison with the equals operator is performed. The exact algorithm is defined in section 11.9.3.
I built a simple tool to demonstrate which algorithm steps are executed: https://felix-kling.de/js-loose-comparison/
string == integerThe step we have to look at is #5:
That means the string
"\n"("\r","\t") is converted to a number first and then compared against0.How is a string converted to a number? This is explained in section 9.3.1. In short, we have:
where
StrWhiteSpaceis defined asThis just means that the numerical value of strings containing white space characters and/or a line terminator is
0.Which characters are considered as white space characters is defined in section 7.3.
string == booleanThe step we have to look at is #7:
How booleans are converted to numbers is pretty simple:
truebecomes1andfalsebecomes0.Afterwards we are comparing a string against a number, which is explained above.
As others have mentioned, strict comparison (
===) can be used to avoid this "problem". Actually you should only be using the normal comparison if you know what you are doing and want this behaviour.