0

While loop question about +=

PLEASE HELP +++ can someone explain me the following code : while (i < 10) {     text += "The number is " + i;     i++; } Why is there used the "+=" symbol? Doesn't it mean, that you add text with text? What sense does it have? It's a code from W3schools. I just don't get that :(

11th Jun 2017, 9:23 AM
Elias Fzada
Elias Fzada - avatar
8 odpowiedzi
+ 2
+= is a composite assignment operator that updates the existing value of variable on the left hand side by adding (appending in your case) rhs value to it. Above code will result into text += "This number is " + I will give This number is 1This number is 2This number is 3....This number is 9
11th Jun 2017, 9:44 AM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
+ 9
in JS + is used (among other things) for concatenating strings. 'a'+'b'='ab', but be careful with that. JS reacts a bit strange sometimes due to the fact that it is an interpretive non-type-strict scripting language which tries to get some result out of anything.
11th Jun 2017, 9:45 AM
Nikolay Nachev
Nikolay Nachev - avatar
+ 2
Let's simply the statement text += "The number is " + i text = text + "The number is " + 1 "The number is " + 1 work from left to right and since its string before + operator, it will concatenate the operand after + operator (auto casting into string) To get arithmetic sum, change code as follows text=0 while (i < 10) {     text +=  i;     i++; }
11th Jun 2017, 11:13 AM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
+ 2
You got it man😉
11th Jun 2017, 12:01 PM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
0
But why is it updated with the code on the right? I thought something would be ADDED. For example it it would be *= the variable on the left side will be multiplied with the variable on the right side. So it should have be 1+3 or am I wrong? I don't get that..
11th Jun 2017, 10:51 AM
Elias Fzada
Elias Fzada - avatar
0
Ok cold on. So if we get back to the code above at the beginning this would mean = Text = text + text, right? Thus : "the number is" + i + "the number is" + i You know what I am trying to say? So is it ADDED or REPLACED? :-) it's a little bit confusing..
11th Jun 2017, 11:41 AM
Elias Fzada
Elias Fzada - avatar
0
Perfect dude!!! :-)
11th Jun 2017, 12:32 PM
Elias Fzada
Elias Fzada - avatar
0
don't department on sololearn. you must learn basics first. see YouTube video like durasoft channel.
11th Jun 2017, 4:49 PM
meherDev
meherDev - avatar