Short operators += and *=



In Javascript, it is often required to change the value of a variable with something like in

x = x + y;

It basically adds y to x and assigns it back to x. Javascript provides a shorter form for this statement.

x += y;

As an example here is the code that

  1. <html>
  2. <body>
  3. <script type="text/javascript">
  4. <!--
  5. /*
  6. ********************************************************
  7. Example compound assignment statement
  8. ReferenceDesigner.com javascript tutorial
  9. ********************************************************
  10. */
  11.  
  12. var x = 2;
  13. var y = 5;
  14.  
  15. x +=3; // Is same as x = x +3, x is now 5
  16. document.write("value of x after x +=3 is :"+ x +"<br />");
  17. x += y; // Is same as x = x + y; x is now 10
  18. document.write("value of x after x +=y is :"+ x);
  19. //-->
  20. </script>
  21. </body>
  22. </html>


If you compile and run, you get the following output


value of x after x +=3 5
value of x after x +=y 10




The addition is not the only operator on which compound assignment statement can operate. It can operate on *, / and other operators as well.

x *= y ; // Is same as x = x*y

x /= y; // Is the same as x = x/y;

x %= y; // Is the same as x = x % y;

x <<= y; // Is the same as x = x<
x &= y; is the same as x = x & y;