JavaScript compound assignment operators

 JavaScript compound assignment operators

The compound assignment operators consist of a binary operator and the simple assignment operator.

We've already studied binary operators, they work with two operands. For example a+b where + is the operator and the a, b are operands. We also know what a simple assignment operator is.

It's quite common to modify a value stored in variables. To make this process a little quicker, we use compound assignment operators.

They are:

  • +=
  • -+
  • *=
  • /=

Let's consider an example. Suppose price = 5 and we want to add ten more to it.

var price = 5; 
price = price + 10; 

We added ten to price. Look at the repetitive price variable. We could easily use a compound += to reduce this. We do this instead.

price += 5;

Awesome. Isn't it? What's the value of price now? Practice and comment below. If you don't know how to practice check these lessons.

Lets bring down the price by 5 again and display it. 
We use console.log command to display what is stored in the variable. It is very help for debugging.
Debugging let's you find errors or bugs in your code. More on this later.

price -= 5;

Lets multiply price and show it.

price *=5;

and finally we will divide it.

price /=5;

If you have any doubts, comment below.

Post a Comment