All of the operators we have considered so far have shared one property: they have left their operands unchanged. This is generally a good thing: generally, we do not want the statement
a = b + c
to change the values of b and c, only of a.
There are a category of operators, however, which do change the values of their operands. These are known as side-effect operators: they produce a value, and, as an additional effect, change the values of the variables to which they are applied. JavaScript has operators of this category.
JavaScript has four unary operators, pre- and post-increment, and pre- and post-decrement, which both produce a value and change the value of the variable to which they are applied. These operators are denoted by ++ (two plus signs) and -- (two minus signs), placed before or after the variable to be affected, respectively. Both the pre- and post-increment operators increase the value of their operand by 1. Both the pre- and post-decrement operators decrease the value of their operand by 1. The pre-increment and pre-decrement operators produce, as their value, the updated value of their operand; the post-increment and post-decrement produce, as their value, the original value of their operand. This behavior can be summarized in the table below:
Expression |
Value of expression |
New value of a |
|---|---|---|
++ a |
Original value of a + 1 |
Original value of a + 1 |
a ++ |
Original value of a |
Original value of a + 1 |
-- a |
Original value of a - 1 |
Original value of a – 1 |
a -- |
Original value of a |
Original value of a - 1 |
These operators are commonly used in indices for counting loops, as described in the Control Flow II section of this tutorial.
Assignment in JavaScript is also an operator, rather than a statement. As such, the expression
a = b
has a value — its value is the value assigned to a. JavaScript also defines a suite of assignment operators that combine another operation with an assignment side-effect. These operators are *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^=, and |=. The effect of each of these is to perform the indicated operation (*, /, %, etc.) on its two operands, assign the result to the left operand, and return the value assigned as the value of the expression.
[ Previous page | Top of page | Next page ]
Copyright © 2002 Brian Hetrick
Page last updated 13 January 2002.
Tutorial
Building Blocks I
Expressions
Side Effect
Control Flow II
Basic I/O
Algorithms
A First Program
Answers
Modularization
Data Structures I
Recursion
Program Attributes
Building Blocks II
Algorithm Analysis
Structuring
Data Structures II
Abstract Types
Objects
Problem Analysis
Reference Card
![]()