WebDevelopersNotes logo

home-icon Home / JavaScript / JavaScript increment and decrement operators – Operator Precedence

JavaScript increment and decrement operators – Operator Precedence

JavaScript increment and decrement operators

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

  • Start by adding 25 to 100 and then multiplying the result with 4… yields 500.
  • Multiplying 100 by 4 and then adding 25… yields 425.

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

Sponsored Links

Your comments
Star icon IMPORTANT Have a question / problem? Click here to ask an expert.

Sponsored Links

Tips

How do I view a deleted web page?
Is there a way to view a deleted web page - one that is no longer available? Yes there is and the solution is quite simple. [more...]

Fact

Brewster Kahle, the creator of the Internet Archive has collected over half a million books! The Internet Archive itself is a collection of websites, music, images and public-domain books. [more...]

We use cookies to give you the best possible website experience. By using WebDevelopersNotes.com, you agree to our Privacy Policy