3 ms·
those are all great explanations. unfortunately they fail to address the "why". i would expect [] + [] to behave like [].concat([]) {} + {} to behave like jqu
by leeoniya 15y ago
those are all great explanations. unfortunately they fail to address the "why". i would expect
[] + [] to behave like [].concat([])
{} + {} to behave like jquery's $.extend({}, {})
anything else should just barf. IMO.
- tikhonj 15y agoI think having both type coercion and overloaded operators is not a good idea. Since JavaScript uses type coercion widely--and I agree with this myself--a better solution would be to have + only do addition. As it, it tries to do too much: both numerical addition and concatenation. If all it did was addition, you could simply coerce both sides to numbers and return NaN if the conversion did not make sense. Of course, this would mean needing an extra operator for concatenation, but I think that would be fine. On the other hand, your approach would make sense if JavaScript did not try to coerce everything. In that case, having + act differently for different types would be a good option, and your ideas would fit right in. In short: the problem is not type coercion and not overloaded operators; the problem is combining the two in one language.
- rat87 15y agoYou could have ++ to do concats like in haskell
- tikhonj 15y agoNo, ++ is already taken. So is . (dot operator). Maybe # would do, but they're thinking of using it for a bunch of other syntax in the future. Anyhow, there's no way to change it without breaking backwards compatability :( And just adding a concatenation operator alone would not do because + would still behave in an annoying way unless it was changed to only do math.
- deleted 15y ago[deleted]
- olavk 15y agoIn JS operators only works on scalar types (number, string or boolean). Operations on objects (including Array) must be methods (like concat, extend), since JS doesn't support operator overloading. Some operators work on numbers (eg. * , /, ++, prefix +), some work on booleans (eg &&, ?:). Infix + is special cased because it works on either strings or numbers. JS uses implicit coercion with operators. An operator will newer throw a type error. Instead the operands are converted into the expected type, e.g `a * b` is equivalent to `Number(a) * Number(b)`. The rules for how objects are converted into scalar values are non-obvious, but then again, you shouldn't use numeric operators on objects in the first place.