Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
You know, for all the hate JS takes for this... It's actually not at all surprising for anyone familiar with C++ operators, and how you can do pretty much all you want with them.
It's pretty much how + works for strings.
The only difference is c++ does not have an implicit conversion from string to number, but you could add it anyway... -
well okay. but then think about it.. what else should "-" do. I mean yea it could through an error. Or just do this :/
-
@joewilliams007
The thing is, in C++ terms, JS 1 + "1" is
operator+(int, std::string&)
With no implicit conversion, that isn't implicitly defined. JS implementors decided to coerce to string because operator+ is defined for two strings, but they could have gone with coercion to number too.
However, coercion to number is more problematic because it can fail, whereas coercion to string is defined for every possible number.
So they went with that.
However, operator - is not defined for two strings, hence, since you already have string to number implicit conversion, the rational thing to do is coerce the string to number and do operator-(int, int).
Hence the actual behaviour, and why it actually makes sense.
We can discuss if implicit string to number conversion makes sense or not, but that's another different issue altogether.
JavaScript 🤯
Credit:whoever made this
joke/meme
javascript