+ 1
String Operators
var x = "50"; var y = "100"; document.write(x+y); It's answer is 50100. But why is output 50100? 50+100=150 So explain me how the answer is 50100?
2 Antworten
+ 6
Because the operator + is polymorphic, it can be used to add numbers or concatenate strings (has more uses)
When doing mathematical operations, Javascript can convert to string when one of the value is string (it's called automatic type conversion),
"luis" + 1 = "luis" + "1"
"luis1"
"1" + 2 = "1" + "2"
"12"
"1" + "2" = "1" + "2"
"12"
1 + 2 = 1 + 2
3
+ 3
+ operator acts differently depending on the given operands. Basically, it acts as string concatenation when one of the operands are string. It acts as number addition when operands are numeric.
In your example, <x> and <y> are string, so in that case, <x> and <y> are glued together.