Home / JavaScript / JavaScript increment and decrement operators – Operator Precedence

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 toa, 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.

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.

**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 = 425ORres = (25 + 100) * 4; res = 500

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...]

The first commercial spam was posted on Usenet by Laurence Canter and Martha Siegel. They used a Perl script to post their message, "Green Card Lottery - Final One?", to about 5,500 discussion groups. [more...]

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