Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About "5"-1 & "5"+1 in Javascript (plus and minus signs) [duplicate]

I read a book about operators in Javascript, and this confused me.

console.log("5"+1);

This would make "5" as a string. So the result would be 51.

console.log("5"-1);

This result would be 4. I know it converts "5" to 5, but why it isn't shown undefined as "a string minus a number"?

Update: So how about other languages? Are they more restrict?

like image 787
chenghuayang Avatar asked May 27 '15 07:05

chenghuayang


1 Answers

Sadly, it was expected from JavaScript to ride on Java's success for promotion on its early days and the plus for string concatenation was adopted since Java used it.

So JavaScript tries hard to coerce strings into numbers for you, it really does, its just that the plus was taken for strings so....well...

While Javascript has many strenghts it was made in 10 days and has many hilarious aspects like this one, check this comedy gold

like image 101
JSelser Avatar answered Oct 14 '22 03:10

JSelser