JavaScript increment and decrement operators – Operator Precedence

JavaScript increment and decrement operators – Operator Precedence cover image
  1. Home
  2. JavaScript
  3. JavaScript increment and decrement operators – Operator Precedence

A note about the increment and decrement operators

Unlike other operators, the increment and decrement operators act on only one operand. They are hence called Unary operators.
They can be used either before or after a variable as in:

   a++;
   b--;

OR

   ++a;
   --b;

When these operators are used as prefixes, JavaScript first adds one to the variable and then returns the value. When used as suffixes, the value is first returned and then the variable is incremented. Let’s know more about this:

   var a = 5;
   b = a++;
	(b contains the initial value of a, which is 5.
	a, on the other hand is now equal to 6)

   var a = 5;
   c = ++a;
	(In this case, JavaScript first adds 1 to a, changing
	its value to 6. This value is returned to c.
	Thus, c = 6)

Read the section again, if you’ve not understood this concept.

Sponsored Links

Operator precedence in JavaScript

Take a look at the following code… what do you think will be the value of variable res?

   var res =  25 + 100 * 4;

There are two ways to look at this

Let us find out how does JavaScript solve the problem
JavaScript has this inbuilt thing called Operator Precedence. It’s a list of operators specifying the order in which they will be executed if two or more are found in the same expression.
In our case, the multiplication operator has a higher precedence than the addition operator. Hence, JavaScript will first multiply 100 with 4 and add 25 resulting in 425.

Do you need to learn the operator precedence table?

NO!
JavaScript expressions (such as the one above) can be made more clear by adding parenthesis. Thus, depending on our need, we can write the statement as:

   res = 25 + (100 * 4);     res = 425
OR
   res = (25 + 100) * 4;     res = 500
JavaScript