News for hackers. Stuff that matters.
Re:Zeros in JavaScript by mistercow on Monday November 04, 2013 @08:10PM (#6672454)
You really wouldn't want an empty object to be equal to zero, since it might have a prototype that gives it functionality (and having the behavior conditional upon that would make it preposterously complicated to use correctly).

The real mistake was making [] equal zero.

Re:Zeros in JavaScript by TazeTSchnitzel on Monday November 04, 2013 @08:14PM (#6672477)
[] doesn't equal zero, but '' does, and [] is coerced to '' which is coerced to 0, IIRC.
Re:Zeros in JavaScript by mistercow on Monday November 04, 2013 @10:16PM (#6672998)
What's really interesting thing is that all numeric coercions go through a string coercion, and that coercion doesn't (at least in Chrome and Firefox) have to even return a string. Presumably, the toString() method is run repeatedly until either a string or a number comes out.

So a simple fraction type can be done like this:

    function Fraction(n, d) {
        this.n = n;
        this.d = d;
    }
    Fraction.prototype.toString = function() {
        return this.n / this.d;
    };
    
    //Demo
    var x = new Fraction(1, 2);
    alert(x * 38); //19
    alert(x + x); //1