I was explaining to a colleague that you should use ===
and !==
(and >==
and <==
of course) when comparing variables in JavaScript so that it doesn't coerce the arguments and get all froopy and confusing but they asked me a two part question that I did not know the answer to and thought I would ask the experts here, specifically it is:
What about
>
and<
- when they compare do they also coerce the arguments or not - why isn't there some sort of>>
and<<
operator (probably need to be some other syntax as I would guess they would be bit shift operators if it is going along the whole C style but you get the gist)?
So I can write a test to find the answer to the first part, which I did, here it is:
// Demo the difference between == and ===
alert(5 == "5");
alert(5 === "5");
// Check out what happens with >
alert(5 > "4");
alert(5 > 4);
and it returned:
true
false
true
true
so it does look like the >
is doing the coercion since > "4"
and > 4
return the same result. so how about the second part...
Is there some sort of operator for >
and <
that do not coerce the type (or how can I change my test to perform the test safely)?