5 ms·
function f(a,b){ return a+b-b } Now tell me, what is f("1",2)? Is this really what you would expect? Treating strings like strings sometimes and integers
by Klockan 12y ago
function f(a,b){
return a+b-b
}
Now tell me, what is f("1",2)? Is this really what you would expect? Treating strings like strings sometimes and integers other times messes up functions, creating bugs that are extremely hard to track. Usually you can get back what you started with if you subtract after you add, but JavaScript ruins that unless you first check that the input are numbers. If it always tried to coerce the string into an integer or vice versa then it would be fine.
- timepiece 12y agoI know that at face value, things look messy and unpredictable but if you really know js in and out, you'd guess the right answer (1) (Check operator precedence and associativity for reference) The problem with people coming from more classical programming languages to learn js is that some have this condescending attitude toward the language from the get go and expect that by the virtue of having C/Java experience under the belt, that everything should look similar in js and when they encounter something like "automatic type casting" they freak out and start dissing the language but once they seriously put the effort to understand it, their frustration and bad experience starts to give away to a more positive experience and consequently more positive sentiment toward the language. So for me it's just a question of attitude and story of prejudice and perceived supremacy of one's own language background at play here.
- Klockan 12y agoIt isn't hard to see the answer, but that wasn't my point. The point is that you want predictable behavior from your functions. If you saw the output of said function for integers you could never have guessed the output of said function with the combination of a string and an integer. JavaScript forces you to work more to get predictable type conversions by having a lot of random conversions. While each of those conversions might make sense the combination of them usually doesn't. Why can I use other maths operators to coerce the string into a number but not '+'? Because '+' is a special case since it tries to coerce to a string before it tries to coerce to an integer, it isn't hard to get that. But it makes the other conversions dangerous since when you want to use '*', '-' or '/' you usually want to use '+' as well but as it is the other works but not '+'. What would make sense is to either remove the special case of '+' or you add special cases for the other operators so that they act similarly as '+' with strings.
- kuschku 12y agoBtw, you guessed the wrong answer – it is actually 10 (as number, not as string). So it is definitely not as easy as you make it seem.
- timepiece 12y agoJust a typo but good catch though :)