Javascript equality triple equals but what about greater than and less than? - javascript

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)?

No, there's no need for such operators. The type checking done for those relational operators is different than for equality and inequality. (edit — perhaps it's a little strong to say that there's "no need"; that's true only because JavaScript deems it so :-)
Specifically, the > and < and >= and <= operators all operate either on two numeric values, or two strings, preferring numeric values. That is, if one value is a number, then the other is treated as a number. If a non-number can't be cleanly converted to a number (that is, if it ends up as NaN), then the result of the comparison is undefined. (That's a little problematic, because undefined will look like false in the context of an if statement.)
If both values are strings, then a collating-order string comparison is performed instead.
If you think about it, these comparisons don't make any sense for object instances; what does it mean for an object to be "greater than" another? I suppose, perhaps, that this means that if you're finding yourself with values of variant types being compared like this, and that's causing problems, then yes you have to detect the situation yourself. It seems to me that it would be good to work upstream and think about whether there's something fishy about the code that's leading to such a situation.

Is there some sort of operator for > and < that do not coerce the type
No.
how can I change my test to perform the test safely
You would have to explicitly test the types:
typeof a === typeof b && a > b

I referenced Flanagan's JavaScript: The Definitive Guide (5th Ed.) and there does not seem to be non-coercive comparison operators.
You are right in saying the << and >> are indeed bitwise operators so that wouldn't work.
I would suggest you deliberately coerce the values youself:
var num_as_string = '4';
var num = +num_as_string;
if (5 > num) { ... }

12 > '100' // false
'12' > 100 // false
'12' > '100' // true
As others mentioned, if one is a number the other is casted to a number. Same rule applies to these cases as well:
null > 0 // false
null < 0 // false
null >= 0 // true
However, there might be cases that you would need null >= 0 to give false (or any of the number string comparison cases above), therefore it is indeed a need to have strict comparison >== or <==.
For example, I am writing a compareFunction for the Array.prototype.sort() and an expression like x>=0 would treat null values like 0's and put them together, whereas I want to put them elsewhere. I have to write extra logic for those cases.
Javascript says deal with it on your own (in practice).

Related

A javascript statement that I haven't seen before

I am inspecting some Javascript code written in UnderscoreJS. In this, there are quite a few instances of JS code being written like this:
if(length === +length){ //do something}
or
if(length !== +length){ //do something }
What exactly does this compute to? I have never seen this before.
if (length === +length)
It makes sure that the length is actually a numeric value.
Two things to understand here,
The Strict equality operator, will evaluate to true only when the objects are the same. In JavaScript, the numbers and strings are immutables. So, when you compare two numbers, the Number values will be compared.
Unary + operator will try to get the numeric value of any object. If the object is already of type Number, it will not make any changes and return the object as it is.
In this case, if length is actually a number in string format, lets say "1", the expression
"1" == +"1"
will evaluate to be true, because "1" is coerced to numeric 1 internally and compared. But
"1" === +"1"
which will be transformed to
"1" === 1
and that will not undergo coercion and since the types are different, === will evaluate to false. And if length is of any other type, === will straight away return false, as the right hand side is a number.
You can think of this check as a shorthand version of this
if (Object.prototype.toString.call(length) === "[object Number]")
It is a way of testing whether a value is numeric. See this for example:
> length="string"
> length === +length
false
> length=2
> length === +length
true
The unary + converts the variable length to the Number type, so if it was already numeric then the identity will be satisfied.
The use of the identity operator === rather than the equality operator == is important here, as it does a strict comparison of both the value and the type of the operands.
Perhaps a more explicit (but slightly longer to write) way of performing the same test would be to use:
typeof length === "number"

Why isn't undefined less than 1?

So in most cases I've been able to use something similar to these lines, but Javascript has given me this weird result.
If I take some value and it turns out to be undefined, when compared to an integer, it does not appear to be less than or greater than any number. Why is this?
if(undefined < 1 || undefined >= 1)
alert("yes");
else
alert("no");
//this always alerts no
JSFiddle
There is no operator '<' can not be applied to type 'undefined' error in JavaScript as you would find in other typed languages. As such, JavaScript evaluates incompatible types with an operator to false.
That's just how javascript works. If either side can't be converted to a number (strings can, by code point comparison: '2' < '3' && '186' < '4'), than number comparisons will return false (works with >, <, <=, >=).
Might be a little tangential, but I'd like to introduce null into this topic to demonstrate an elusive pitfall.
When using <, <=, >, >= with null or undefined, the result is generally considered to always be false. However, there's one exception: Infinity
console.log(undefined < Infinity); // false, as expected
console.log(null < Infinity); // true, surprise!
Also notably, this also applied to the string "Infinity"
console.log(undefined < "Infinity"); // false
console.log(null < "Infinity"); // true, surprise again!
console.log(null < "infinity"); // false, it's case-sensitive
I discovered this weird behavior accidentally, and have no idea why the hell JavaScript behaves this way. But anyway, like it or not, this is JavaScript.
Hopefully, this may help someone one day.

Why eval("475957E-8905") == "475957E-8905" is true?

I made a program with nodeJs which generate code such as
eval("XXXXXX") == "XXXXXX"
It's working pretty well, but at a moment he gave me this :
eval("475957E-8905") == "475957E-8905"
I tested it with Firebug, and the result is true
.But I don't really understand why.
Of course, eval("475957E-8905") return 0
but why 0 == "475957E-8905" ?
There are two pieces to this puzzle: floating-point numbers and type-insensitive comparison using ==.
First, 475957E-8905 evaluates as the floating point number 475957 * 10 ^ -8905, which is incredibly small; in floating-point terms, it's the same as 0 due to the precision limitations of javascript. So, eval("475957E-8905") returns 0.
Now, for the second piece of the puzzle.
The == means that the types don't have to match, so nodejs (like any JavaScript engine) tries to convert one of them so it can compare them.
Since eval("475957E-8905") returned 0, it tries to convert "475957E-8905" to an integer as well. As we have seen, that is also 0. Thus, the comparison is 0 == 0, which is true.
Note that the same thing happens if you do eval("3") == "3" or eval("3") == 3 -- in each case, the strings are converted to numbers and compared.
Avoiding this problem
You can force a type-sensitive comparison like this:
eval("475957E-8905") === "475957E-8905"
which returns false, because the === tells the javascript engine to return true only if the types and the values both match.
Javascript has to convert your string, "475957E-8905", to a number in order to compare them. When it does that, it converts "475957E-8905" to 0 as well. So, 0 == 0;
As you can see:
"475957E-8905" == 0
Is true. Basically you eval statement "475957E-8905" into a number, and then the other "475957E-8905" is being converted to a number for comparison. In the end, the exact same conversion process has happened to both of them and they are both 0.
use === to compare the type as well, for further information:
JavaScript has both strict and
type-converting equality comparison.
For strict equality the objects being
compared must have the same type and:
Two strings are strictly equal when they have the same sequence of
characters, same length, and same
characters in corresponding positions.
Two numbers are strictly equal when they are numerically equal (have
the same number value). NaN is not
equal to anything, including NaN.
Positive and negative zeros are equal
to one another.
Two Boolean operands are strictly equal if both are true or
both are false.
Two objects are strictly equal if they refer to the same Object.
Null and Undefined types are == (but not ===). [I.e. Null==Undefined (but not Null===Undefined)]
check this documentation

Why use logical operators when bitwise operators do the same?

Consider this condition:
(true & true & false & false & true) == true //returns: false
As you can see, the bitwise AND behavior is exactly like logical AND's:
(true && true && false && false && true) == true //returns: false
I'm wondering why I should use logical operations when the bitwise operations do the same as the logical ones.
Note: Please don't answer that's because of performance issue because it's pretty much faster in Mozilla Firefox, see this jsPerf: http://jsperf.com/bitwise-logical-and
The most common use of short-circuit evaluations using logical operators isn't performance but avoiding errors. See this :
if (a && a.length)
You can't simply use & here.
Note that using & instead of && can't be done when you don't deal with booleans. For example & on 2 (01 in binary) and 4 (10 in binary) is 0.
Note also that, apart in if tests, && (just like ||) is also used because it returns one of the operands :
"a" & "b" => 0
"a" && "b" => "b"
More generally, using & in place of && is often possible. Just like omitting most ; in your javascript code. But it will force you to think more than necessary (or will bring you weird bugs from time to time).
bitwise operations behavior the same?
No, it's not. Bitwise operators work on integer numbers, while the logical operators have stronlgy different semantics. Only when using pure booleans, the result may be similar.
Bitwise operators: Evalutate both operands, convert to 32-bit integer, operate on them, and return the number.
Logical operators: Evaluate the first operand, if it is truthy/falsy then evalutate and return second operand else return the first result. This is called Short-circuit evaluation
You already can see this difference in the type of the result:
(true & true & false & false & true) === 0
(true && true && false && false && true) === false
No they don't do the same. The differences are:
Whether the operand types are converted
Whether both operands are evaluated
The return value
// sample functions
function a() { console.log("a()"); return false; }
function b() { console.log("b()"); return true; }
&& (Logical AND)
Checks the truthiness of operands
Uses short-circuiting and may not evaluate the second operand
Returns the last evaluated operand without type conversion
a() && b();
// LOG: "a()"
// RET: false
& (Bitwise AND)
Temporarily converts the operands to their 32bit integer representation (if necessary)
Evaluates both operands
Returns a number
a() & b();
// LOG: "a()"
// LOG: "b()"
// RET: 0
Almost everything is already said, but just for completeness' sake I want to take a look at the performance aspect (which you said doesn't matter, but it very well might):
JavaScript has a lot of difficult-to-remember rules on how to evaluate expressions. This includes a lot of type casting (implicit type coercion) when it comes to more complex comparisons. Arrays and Objects need to be converted by calling their toString() methods and are then cast to numbers. This results in a huge performance hit.
The logical operator && is short-circuiting. This means as soon as it encounters a falsy value, the evaluation stops and false is returned. The bitwise operator will always evaluate the entire statement.
Consider the following (yes, quite extreme) short circuit example when very expensive operations (casting an array and an object) are involved: ( performance according to https://jsbench.me in Chromium 90)
// logical operator
( false && {} && [] ) == true
// /\ short circuits here
// performance: 805M ops/sec
// bitwise operator
( false & {} & [] ) == true // evaluates the entire statement
// performance: 3.7M ops/sec
You can see that the performance differs by a factor of 100!
Because using && or & convey different intents.
The first says you're testing truthiness.
The second means your conjuring up some bit magic. In real code, you will be looking at variable1 & variable2. It will not be clear that you're in fact intending to test for truth (not truthiness). The reader of the code will probably be confused because it's not obvious why & was used.
Furthermore, the semantics are completely different when taking into account other values than bools and function calls, as pointed out by numerous other posts.
Boolean allows short-circuiting, which can be a performance boost or safety check.
Non-boolean values used in the conditional. For example, if ( 1 & 2 ) will return false, whereas if ( 1 && 2 ) will return true.
You can't short-circuit bitwise operators. Also the bitwise operators can do much more, not just compute a boolean expression.
There's a huge difference: logical operations are short circuited. It means that (true && true && false ) is the last thing to be executed. This allows powerful constructs, such as abstract factory model using var myFunc = mozilla.func || opera.sameFunc || webkit.evenOneMoreVariationOfTheSameConcept;
All subexpressions of bitwise operations have to be fully evaluated -- and btw. one only rarely needs to evaluate constant bitwise or logical expressions anyway.
First condition have to convert first and sum bits then. But second will check logical and return value.
So First one will be slower than second one.
Run This Test: http://jsperf.com/bitwise-logical
on Chrome & IE Bitwise is slower
but on FireFox logical is slower
Bitwise operators (& and |) converts the two operands to 32 bit "integers" and return the bit operation as a result. The conversion of an operand is 0 if it is not numeric.
The logical operators (&& and ||) are not logical at all, but rather are selectors of one of the operands or 0.
The logical && returns the first operand if both exist, otherwise 0
The logical || returns the first existing operand, otherwise 0
An operand exists if not: undefined, null, false, or 0
var bit1 = (((true & true) & (false & false)) & true), // return 0;
bit2 = (((true && true) && (false && false)) && true); // return flase
alert(bit1 + ' is not ' + bit2);

Javascript if-statement vs. comparsion

Is it true that in if-statement JavaScript wrap the condition into a Boolean?
if(x) => if(Boolean(x))
Is it true that in comparison JavaScript wrap the compare elements into a Number?
a == b => Number(a) == Number(b)
Yes, and No.
For the first part, yes, that is essentially what the javascript does.
But for the latter, no. Not everything in JavaScript can be converted to a number. For example:
Number('abc') // => NaN
And Not-A-Numbers are not equal:
NaN == NaN // => false
So something like this:
Number('abc') == Number('abc') // => false!
But that's actually true with equality comparison.
'abc' == 'abc' // => true
As a side note, it's probably better to use === in JavaScript, which also checks the type of the values being compared:
0 == '0' // => true
0 === '0' // => false, because integer is not a string
More details about === can be read over here.
Yes, that's true, x is evaluated in a boolean context in this situation, so the equivalent of Boolean(x) is applied.
No, that's not true. It only looks that way because the coercitive equality operator == tries to convert a and b to the same type. Number() is only applied if either a or b is already a Number. For instance:
>>> 0x2A == 42
true // both 'a' and 'b' are numbers.
>>> "0x2A" == 42
true // 'a' is a string whose number coercion is equal to 'b'.
>>> "0x2A" == "42"
false // 'a' and 'b' are different strings.
Is it true that in if-statement JavaScript wrap the condition into a Boolean?
Usually yes.
Is it true that in comparison JavaScript wrap the compare elements into a Number?
Absolutely no.
Explanation
From JavaScript Language Specifications.
The if statement is defined at § 12.5 as:
if ( Expression ) Statement else Statement
It says that the Expression will be evaluated, converted with GetValue() and then tested after the ToBoolean() conversion.
Then the first assertion is true (but see later), the condition for the if statement is evaluated like is passed as parameter to the Boolean function. Please recall how JavaScript handles type conversion to boolean (§ 9.2):
undefined and null values are converted to false.
numbers are converted to false if ±0 or NaN otherwise they're converted to true.
strings are converted to false if empty otherwise always to true regardless their content.
objects are always converted to true.
Because of the call to GetValue() strictly speaking this assertion is not always true, take a look to § 8.7.1 where the standard describes how GetValue() works, here can happen some magic conversion before ToBoolean() is called.
The == operator is defined as in § 11.9.3.
As you can see it doesn't specify that operands must be (or will be treated as) numbers, the behavior of the operator is different and regulated by a series of rules based on the type of the operands. Then your second assertion is false. The case they're numbers (or one of them is a number) is just a special case in the algorithm, please note that at point 4 of the algorithm it says that if one of them is a number and the other one is a string then it'll be converted with ToNumber(), only in this case (with all the implications that this conversion has).
It's intuitive if you think that you can compare functions, strings or numbers, not every type can be converted to a numeric value.

Categories

Resources