JAVASCRIPT Tutorial

Unary Operators

Unary operators are operators that operate on a single operand. They are often used to modify the value of a variable or to perform logical operations.

Types of Unary Operators

The most common unary operators are:

  • Negation (-): Negates the value of the operand.
  • Increment (++): Increases the value of the operand by 1.
  • Decrement (--): Decreases the value of the operand by 1.
  • Logical NOT (!): Reverses the truthiness of the operand.
  • Unary Plus (+): Converts the operand to a positive number.
  • Unary Minus (-): Converts the operand to a negative number.

Practical Steps

To use a unary operator, simply place it in front of the operand. For example:

let x = 10;
x = -x; // x is now -10

Javascript Example

The following Javascript code demonstrates the use of unary operators:

const a = 5;
const b = -a; // b is -5
const c = ++a; // a is now 6 and c is 6
const d = --b; // b is now -6 and d is -6
const e = !true; // e is false
const f = +10; // f is 10
const g = -20; // g is -20

Conclusion

Unary operators are a powerful tool that can be used to perform a variety of operations on variables. By understanding how to use these operators, you can write more efficient and concise code.