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
| Operator | Name | Description |
|---|---|---|
| + | Unary Plus | Converts operand to a number |
| - | Unary Negation | Negates the value |
| ++ | Increment | Increases value by one |
| -- | Decrement | Decreases value by one |
| ! | Logical NOT | Negates boolean value |
| typeof | Type Operator | Returns the data type |
| delete | Delete Operator | Removes a property from an object |
| void | Void Operator | Evaluates 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 againLogical NOT
let isAvailable = false;
console.log(!isAvailable); // truetypeof 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.
++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.” 🔧