Hacker News new | ask | show | jobs
by timepiece 4108 days ago
I 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.

2 comments

It 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.

Btw, 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.

Just a typo but good catch though :)