+ 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?

18th Feb 2019, 1:09 PM
Nidhi
7 Answers
+ 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 :)
18th Feb 2019, 5:42 PM
avatarluca
avatarluca - avatar
+ 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).
19th Feb 2019, 7:57 AM
Sonic
Sonic - avatar
+ 3
Thank you very much Electron for this explanation.
18th Feb 2019, 5:50 PM
Nidhi
+ 2
Thanks😁😁
24th Feb 2019, 10:30 AM
M.i.m.a😍😍😍
M.i.m.a😍😍😍 - avatar
+ 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.
19th Feb 2019, 5:30 PM
Ansh Choudhary
Ansh Choudhary - avatar
+ 1
JavaScript is a loosely typed languages..that is the main reason
20th Feb 2019, 4:33 AM
Oly
Oly - avatar
0
Good
19th Feb 2019, 12:52 PM
Marcellinus Acquaye
Marcellinus Acquaye - avatar