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
|
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;