g
Printer Friendly Version

editor  
BellaOnline's JavaScript / Java Editor
 

JavaScript Increment and Decrement

JavaScript has a number of arithmetic operators that are similar to what you know from elementary math, but it also has some that are specific only to programming languages. The most common and useful of these are probably the increment and decrement operators. If you've looked at any JavaScript code, you have very likely seen these operators used on counters (often called i or cnt by convention), such as i++.

The Increment and Decrement Operators
OperatorSymbolPurposeExampleResult
Increment
++
increment by 1
4++
5
Decrement
--
decrement by 1
4--
3


The interesting and sometimes confusing thing about the increment and decrement operators is that they have two forms – prefix and postfix notation – which act slightly differently. Prefix notation is when the operator ("++" or "--") is in front of the number or variable – for instance, --i or ++cnt. Postfix notation is when the operator ("++" or "--") is placed after the number or variable – for instance, i++ or cnt--.

When used in an expression (equation), prefix notation means the increment or decrement takes place before the number or variable is used. In postfix notation, the original value of the number or variable is used and then the increment or decrement takes place. This is easiest to understand by looking at how it works.

Prefix NotationPostfix Notation
Codea=4
b=++a + 2
a=4
b=a++ + 2
ResultThe increment takes place first resulting in the following values:
a=5
b=7
The addition take place first resulting in the following values:
a=5
b=6


Prefix and postfix notation can be confusing, however, a few things make it easier. In the vast majority of cases, the increment and decrement operators are used on their own or in parenthesis. When the increment and decrement operators are used on their own (as they often are when used as loop counters), the prefix and postfix versions work identically. The same is true when they are used in parenthesis. To avoid confusing yourself or other people reading your code, it's a good idea to use increment and decrement operators in expressions sparingly and with parenthesis whenever possible.

This site needs an editor - click to learn more!

JavaScript / Java Site @ BellaOnline
View This Article in Regular Layout

Content copyright © 2013 by Julie L Baumler. All rights reserved.
This content was written by Julie L Baumler. If you wish to use this content in any manner, you need written permission. Contact Editor Wanted for details.



| About BellaOnline | Privacy Policy | Advertising | Become an Editor |
Website copyright © 2023 Minerva WebWorks LLC. All rights reserved.


BellaOnline Editor