Next page | Contents page |

Operators

Arithmetic:
+ add
- subtract
* multiply
/ divide
% modulus (remainder)

+ is also used to concatenate strings: s = "Hello " + name;

++ and -- increment and decrement by 1, commonly for loops:


	x++;           // Increment x (by 1)
	a = x++  + y;  // a = x + y, then increment x
	b = --x * y;   // Decrement x then b = x * y

Boolean operators:
&& AND
|| OR
! NOT

Comparisons:
== is equal to
=== is identical to
!= is not equal to
!== is not identical to
> is greater than
>= is greater than or equal to
< is less than
<= is less than or equal to

The difference between being equal to and being identical to, we will see later.

Assignment:
= (never to be confused with == or ===)

We have already seen several examples. An expression is evaluated and the result is assigned to the variable on the left hand side:


  x *= 3.14;   // Shorthand for x = x * 3.14;
  var paid = true;
  var fullName = firstName + "  " + lastName;
  r2 = x * x + y * y;
  var r = squareRoot (r2); // result from a function

NB: If nothing has yet been assigned to a variable declared with var it has the special value undefined.

The conditional operator: ? :
eg, var s = (x == y) ? firstName + " " : initial;
If the condition is true do the statement between ? and :, otherwise do the statement after the colon.
NB: Use this sparingly - it's hard to read

There are also compound operations of the form op=
+= -= *= /= %= &= |= ^= <<= >>= >>>=
eg,


	a %= b; 	// is shorthand for:
	a = a % b;

Next page | Contents page |