What is Unary Operator in JavaScript ?
Unary operator is that operator which works on one or single operand.
Types of Unary Operators
- Increment Operators (++)
- Decrement Operators (--)
Further, Increment operators are of two types:
- Pre-increment Operator (++num).
- Post-increment Operator (num++).
and, Decrement operators are of two types:
- Pre-decrement Operator (--num).
- Post-decrement Operator (num--).
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:
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:
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:
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:
num2=10