1

I was writing some javascript code and instead of writing $("p").append(a +", "); i mistyped it as $("p").append(a +=", ");.

After i ran the script the result was quite peculiar. I have created this Fiddle. Click on the button 3,4 times and the result would be something like this : 0, 0, , 0, , , 0, , , ,.

As I am a beginner in javascript maybe i don't know some syntax which is causing this behaviour. Also i wasn't able to find any references to a similar problem anywhere. I want to understand how this is happening.

  • @fvu I think the confusion was due the fact that when we write `(a+",")` it actually prints the value of `a` concatenated with `,`. Thanks for pointing it out though :) – Himanshu Dabas Sep 13 '17 at 12:10

5 Answers5

4

For every click the value of a changes.

", " is added every time the button is clicked. Since you set a to 0 only at the beginning it keeps on getting longer.

This is caused because of +=.

Writing a += ", " is equivalent of writing a = a + ", ".

Luka Čelebić
  • 1,083
  • 11
  • 21
1

a += ", " is the same as a = a + ", ". So every time you click it, a is being modified to have another ", " at the end of it.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
1

a += ", " is the same as a = a + ", "

Basically what is happening is this. You start with the number 0. When you hit the button the first time, 0 becomes the string "0,", when you hit it a second time, you're saying "to the string 0, add the result of concatinating the string 0, and ," which gives us a string of 0,0,, ("0," + ("0," +",")), every time you click the button, the operation is repeated

TheCog19
  • 1,129
  • 12
  • 26
1

Everytime you hit the button, you are adding a comma and a space to the variable a.

+= is shorthand for a = a + ', '

JOSEFtw
  • 9,781
  • 9
  • 49
  • 67
0

Your mistype is equivalent to

a = a + ", ";
$("p").append(a);

That is you are repeatedly concatenating ", " to a.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483