Unary Operators in JavaScript

🔍 What Are Unary Operators?

Unary operators are operators that operate on only one operand. In JavaScript, they are used to perform operations like type conversion, negation, incrementing, and more.

>>“One operand, one action — that’s the power of unary operators.” ⚙️

📌 Common Unary Operators

OperatorNameDescription
+Unary PlusConverts operand to a number
-Unary NegationNegates the value
++IncrementIncreases value by one
--DecrementDecreases value by one
!Logical NOTNegates boolean value
typeofType OperatorReturns the data type
deleteDelete OperatorRemoves a property from an object
voidVoid OperatorEvaluates an expression and returns undefined

🧪 Examples in Action

Unary Plus and Minus

let str = "5";
console.log(+str);   // 5 (string to number)
console.log(-str);   // -5 (negated number)

Increment and Decrement

let a = 1;
a++;  // a = 2
--a;  // a = 1 again

Logical NOT

let isAvailable = false;
console.log(!isAvailable); // true

typeof Operator

console.log(typeof 123);       // "number"
console.log(typeof "Hello");  // "string"
console.log(typeof {});       // "object"

delete Operator

const user = { name: "John", age: 30 };
delete user.age;
console.log(user); // { name: "John" }

void Operator

console.log(void 0); // undefined
console.log(void (2 + 2)); // undefined

⚠️ Important Notes

Note

Prefix vs Postfix:
++a increments before usage, a++ increments after usage.

Note

typeof null === "object" is a known JavaScript quirk and considered a bug.

📚 When to Use Unary Operators

  • ✔️ Type conversion from string to number
  • ✔️ Safely negating boolean values
  • ✔️ Quick property deletion
  • ✔️ Checking variable type before operations

🔗 Further Reading

>>“Unary operators — the tiny tools that do big things with one move.” 🔧