es5 bug, operator == and valueOf
On Nov 30, 2010, at 3:25 PM, Fyodorov Bga Alexander wrote:
@apipkin have found logic bug
{valueOf: function(){ return 1 }} == {valueOf: function(){ return 1 }}
// false{valueOf: function(){ return 1 }} >= {valueOf: function(){ return 1 }}
// true, ok
This is not a bug in ES5, although you could argue it's a design flaw in JS. Recall that
typeof a == typeof b && a == b <=> a === b // implies, in both directions
Two object initialisers never evaluate to the same object reference, and === compares references, and == here has same-typed (object) operands, so it is the same as ===.
Relational operators do convert objects. You could argue this is a design flaw; or that this is a win but then == should convert objects as well -- but if that is a flaw, it's only in hindsight, since === came after == and without === there would be no way to distinguish object references without implicit conversion.
Really, implicit conversions (not the same as operator methods) are a design flaw in my view. They make == (ignoring NaN) not an equivalence relation.
But again, not an ES5 bug. Did you read ES1-3 on == and valueOf differently?
Has an operator like >== ever been proposed? So the "strict" relational
operator that returns NaN if typeof left and right don't match. If so, why was it shot down? Bloat? Relatively useless?
On Wed, Dec 1, 2010 at 2:45 AM, Peter van der Zee <ecma at qfox.nl> wrote:
Has an operator like >== ever been proposed? So the "strict" relational operator that returns NaN if typeof left and right don't match. If so, why was it shot down? Bloat? Relatively useless?
Well, > is used more often than >=. How would you spell "strict >"?
I think when people use >, >=, etc. they almost always suppose
(correctly or incorrectly) that the operands are sure to be both
numbers (or both strings). If they aren't, the programmer's
assumptions have already been violated; the code will likely misbehave
whatever answer the language gives. That is, even if the language
provided strict comparisons, and people used them, it probably
wouldn't help. This stands in contrast to code like if (x == undefined)
where there may be no presupposition at all about what
sort of value x is.
@apipkin have found logic bug
{valueOf: function(){ return 1 }} == {valueOf: function(){ return 1 }}
// false{valueOf: function(){ return 1 }} >= {valueOf: function(){ return 1 }}
// true, ok