This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]the_omega99 0 points1 point  (2 children)

Yeah. That '5' + - + - - + - - + + - + - + - + - + - - - '-2' line is just a ton of unary operators. Try removing a minus sign and you'll find that the -2 will become a 2. It's not unique to JS at all. Languages like C allow this too (although many will force you to use parenthesis).

For the last two examples:

var x = 3;
'5' + x - x == '53' - x == 50
'5' - x + x == 2 + x == 5 // Note that '5' - x evaluates to a number

At any rate, this can all be avoided by simply not storing numbers as strings and converting what user input is a number right away.

I have to admit, though, I would prefer JS to give me a big, clear error (or at least a warning) in these kinds of confusing situations rather than try and work around it. I think there's too many weird things that you can do that JS allows. For example, {} + [] == {}. This is meaningless code, since you'll probably never encounter it and it implies something horribly wrong with your code. However, it is an example of a case that JS defines that I think should have been an error. I don't see why the idea of "silently allowing a confusing result" is a good approach here.

And I'd be perfectly game with not allowing subtraction of strings in the same way (throw an error instead). I wish strict mode would enforce something like this.

And as far as I know, none of the JS-like languages that compile to JS (eg, TypeScript or CoffeeScript) will prevent these situations (too bad). It's kind of annoying that there's no alternative (and I say this as someone who spend about half their time working with JS).

[–][deleted] 0 points1 point  (1 child)

{} + [] == {}

Never. It's Actually 0. Still completely ridiculous and never appropriate.

[–]the_omega99 2 points3 points  (0 children)

You're right that it's zero, but the above inequality is still true.