Page 89 - DCAP202_Fundamentals of Web Programming
P. 89
Description
Operator
Example
Simple assignment operator, Assigns
values from right side operands to left
=
of A + B into C
side operand
Add AND assignment operator, It adds
C += A is equivalent to C = C
+=
right operand to the left operand and
+ A
assign the result to left operand C = A + B will assigne value
Subtract AND assignment operator, It
subtracts right operand from the left C -= A is equivalent to C = C
-=
operand and assign the result to left - A
operand
Fundamentals of Web Programming
Multiply AND assignment operator, It
multiplies right operand with the left C *= A is equivalent to C = C
*=
operand and assign the result to left * A
operand
Notes
Divide AND assignment operator, It
divides left operand with the right C /= A is equivalent to C = C
/=
operand and assign the result to left / A
operand
Modulus AND assignment operator, It
C %= A is equivalent to C =
%= takes modulus using two operands and
C % A
assign the result to left operand
Notes Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=,
|= and ^=.
7.1.4 Increment Operators
There are also the increment and decrement operators, ++ and —. a++ increments a and returns
the old value of a. ++a increments a and returns the new value of a. The decrement operator
functions similarly, but reduces the variable instead.
As an example, the last three lines all perform the same task:
var a = 1;
a = a + 1;
a += 1;
++a;
Pre-and Post-increment Operators
Increment operators may be applied before or after a variable. When they are applied before a
variable they are pre-increment operators, and when they are applied after a variable they are
post-increment operators.
!
Caution The choice of which to use changes how they affect operations.
// increment occurs before a is assigned to b
var a = 1;
var b = ++a; // a = 2, b = 2;
// increment occurs to c after c is assigned to d
var c = 1;
var d = c++; // c = 2, d = 1;
!
Caution Due to the possibly confusing nature of pre-and post-increment behaviour, code
can be easier to read if the increment operators are avoided.
// increment occurs before a is assigned to b
var a = 1;
a += 1;
var b = a; // a = 2, b = 2;
// increment occurs to c after c is assigned to d
var c = 1;
82 LOVELY PROFESSIONAL UNIVERSITY