Java Script


JavaScript Tutorial


Admission Enquiry Form

What is Unary Operator in JavaScript ?

Unary operator is that operator which works on one or single operand.

Types of Unary Operators

  1. Increment Operators (++)
  2. Decrement Operators (--)

Further, Increment operators are of two types:

  1. Pre-increment Operator (++num).
  2. Post-increment Operator (num++).

and, Decrement operators are of two types:

  1. Pre-decrement Operator (--num).
  2. Post-decrement Operator (num--).
unary operator in javascript by compuhelp

1. So, in the above image ++ is increment operator and -- is decrement operator. Here num is a variable or an operand.

2. ++ adds 1 to the operand whereas -- subtracts 1 from the operand.

3. num++ increases the value of a variable 'num' by 1 and num-- decreases the value of num by 1.

4. Similarly, ++a increases the value of a variable 'num' by 1 and num-- decreases the value of num by 1.

Example of pre increment operator:


<html>
<head>
<title>Example of pre increment operator</title>
</head>
<body>
<script>
var num1=10, num2;
num2=++num1;
document.write("num1="+num1+"<br>");
document.write("num2="+num2);
</script>
</body>
</html>


Output:

num1=11
num2=11


Example of post increment operator:


<html>
<head>
<title>Example of post increment operator</title>
</head>
<body>
<script>
var num1=10, num2;
num2=num1++;
document.write("num1="+num1+"<br>");
document.write("num2="+num2);
</script>
</body>
</html>


Output:

num1=11
num2=10

Example of pre decrement operator:


<html>
<head>
<title>Example of pre decrement operator</title>
</head>
<body>
<script>
var num1=10, num2;
num2= --num1;
document.write("num1="+num1+"<br>");
document.write("num2="+num2);
</script>
</body>
</html>


Output:

num1=9
num2=9

Example of post decrement operator:


<html>
<head>
<title>Example of post decrement operator</title>
</head>
<body>
<script>
var num1=10, num2;
num2=num1--;
document.write("num1="+num1+"<br>");
document.write("num2="+num2);
</script>
</body>
</html>


Output:

num1=9
num2=10