What You'll Learn
You'll discover how the unary + and - operators work on single values to convert them to numbers and flip their signs.
Understanding Unary Operators
While you've used + and - between two values (like 5 + 3), these operators can also work on one value. When used this way, they're called unary operators.
Unary Plus (+)
The unary + operator converts a value into a number. Think of it as asking JavaScript, "What's the numeric version of this?"
let str = "42";
let num = +str; // 42 (now a number, not a string)
let bool = true;
let numBool = +bool; // 1
let empty = "";
let numEmpty = +empty; // 0
This is especially useful when you receive string input but need to perform math:
let age = "25";
let nextYear = +age + 1; // 26 (not "251"!)
Unary Negation (-)
The unary - operator converts a value to a number and flips its sign (positive becomes negative, negative becomes positive):
let positive = 10;
let negative = -positive; // -10
let strNum = "15";
let negNum = -strNum; // -15 (converted AND negated)
You can even double-negate:
let val = 7;
let result = -(-val); // 7 (back to positive)
Common Use Cases
- Converting string numbers from user input:
+userInput - Negating calculations:
-total - Quick type coercion:
+myVariable
Key Takeaway: Unary + coerces any value to a number, while unary - coerces to a number and negates it—both work on a single value, not between two values.