You call it strange, I call it broken. Python has strong types, so does Erlang. Javascript has weak types and I don't like it.
Whether one can avoid it or not is a different argument, as obviously there aren't that many choices on the browser, but I often argue it is a broken behavior, it annoys me every time I have to use Javascript.
Re:Zeros in JavaScript
by peterashford on Monday November 04, 2013 @09:41PM
(#6672874)
I program JS as my day job. It's a broken POS. You can do cool things with it but nothing can disguise the fact that it's only popular due to an accident of history, not because it's an appropriate language for the tasks it's used for.
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.
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
Re:Zeros in JavaScript
by TazeTSchnitzel on Monday November 04, 2013 @08:10PM
(#6672450)
The undefined.jpg thing won't happen for variables in strict mode, it'll error.
[].length is what you want for the second. IIRC [] isn't false in Python either.
[] is false in Python; so are other empty aggregates like () and {}; collection types implemented in Python typically follow the same pattern. Thus:
>>> if (): print "tuple"
>>> if []: print "list"
>>> if {}: print "dict"
>>> if set(): print "set"
>>> if "": print "string"
>>> import collections
>>> if collections.Counter(): print "counter"
>>> if collections.deque(): print "deque"
>>>
(Observe that none of these prints anything.)
Re:Zeros in JavaScript
by TazeTSchnitzel on Monday November 04, 2013 @08:20PM
(#6672507)
Huh, I recall [] not working. Interesting.
Re:Zeros in JavaScript
by kevin-brown on Monday November 04, 2013 @08:19PM
(#6672502)
[] is false in Python, along with most empty types.
The lesson is, always look for a method that does what you want.