The simplest operators in JavaScript are unary operators. The unary operators are applied to only one value (thus the name "unary").

These operators may be used to increment / decrement a variable's value, or to add / subtract other values to or from it.

Increment / Decrement

To increment or decrement a value, a double plus ("++") or a double minus ("--") may be used in front (prefix) or after (postfix) a variable, as shown here:

var year = 2013;

++year;

--year;

The operation ++year; is equal to year = year + 1;.

When the operators are placed in front (++year;) of a variable, a script first performs the operation and then evaluates the statement. But if the operators are placed after the variable (year--;), then the operation occurs after the statement has been evaluated first. This small but important feature gets obvious when a unary operation is mixed up with other kinds of operation. as shown below:

var num = 10;

var sub = 2;

var res1 = --sub + num; // equals 11

var res2 = sub-- + num; // equals 12

Plus / Minus

The unary plus / minus operation are performed by placing only one operator ("+" or "-") before the variable, as shown below:

var num = 20;

   num = +num; // remains 20

As seen above the value itself remains the same; therefore the real purpose of these operations is to modify the sign of a variable, like this:

var num = 20;    

   num = -num; // equals -20

The unary operations may be used on other values but numbers in which case the rules for conversion to numbers apply.

Example

The example with unary operators in JavaScript:

 

›› go to examples ››