3 ms·
Or you could do the much more sane Perl/Tcl thing and just have different pairs of operators for strings and numbers. Then the type of the variable is determine
by PeCaN 11y ago
Or you could do the much more sane Perl/Tcl thing and just have different pairs of operators for strings and numbers. Then the type of the variable is determined by what you're doing to it, not by what you last did to it somewhere else and god knows whether or not your == will be transitive this time around.
$str1 . $str2 will always be treated as strings, even if both are numbers (I'll get "53" not 8, if $str1 eq 5 and $str2 eq 3). $num1 + $num2 will either coerce them to numbers or fail, and I'll never end up with "5three".
Perl and Tcl might be debateably insane, but they make very sane choices when it comes to weak typing. Funny how a language where literally everything is a friggin' string has a more sane type system than JavaScript.
- emodendroket 11y agoExcept for + and == isn't that true of most operators in JS?
- PeCaN 11y agoYeah that's kind of the problem, those happen to be the two most commonly used operators. All the other arithmetic operators try to convert too ('5' - 3 === 2), but at least produce NaN if the arguments can't coerce to numbers (an exception would be better IMO, but whatever). Bitwise operators consider non-numeric strings to be 0, not NaN, presumably because JavaScript bitwise operands are always considered to be signed 32-bit ints. Apparently ~'js' isn't a TypeError. ¯\_(·ω·)_/¯