+ 10
In Javascript, " 5\n " + 2 = 5 2 2 + "5\n" = 2 5 "5\n" - 2 = 3 2 - "5\n" = -3 Why is it so?
7 ответов
+ 7
In JavaScript you have 2 (basically more but thats not important) variants of using the + operator. The arithmetic one, where + stands for the arithmetic operation "plus" and the other one to joining strings respectively add string/char parts together (like some other languages).
In your first example JavaScript interprets both as the second one, because one element is a string, so it will put it together. In the second one (with - operator) its clear. JavaScript regulary knows one part to use this operator (arithmetic). So it will interpret automaticaly any string or char types as a number (int etc.), if its a string with no number it will give a error. So in your case it will just calc automatically 5 - 2 respectively 2 - 5.
I hope I could help :)
+ 5
The - operator is only used for arithmetic subtraction whereas the + operator is used for both string concatenation (if one of the operands is a string) as well as for arithmetic addition (if no operands are strings).
+ 3
Thank you very much Electron for this explanation.
+ 2
Thanks😁😁
+ 1
In the first two lines, \n is tab space. The + sign concates the string and the number 2.
In next two lines, - is used for only arithmetic operation.
+ 1
JavaScript is a loosely typed languages..that is the main reason
0
Good