JavaScript Unary Plus (+) & Negation (-) Operators

๐Ÿ“˜ What are Unary Operators?

Unary operators work with one operand (one value). Unlike binary operators (such as + or *), unary operators apply to a single value.

โž• Unary Plus Operator (+)

The unary plus operator converts its operand into a number. It is often used to convert strings to numbers.

let x = "10";
let y = +x;

console.log(y);       // 10
console.log(typeof y); // number
            
โœ… Unary plus is a fast way to convert strings to numbers.

โž– Unary Negation Operator (-)

The unary negation operator changes the sign of a number. It can also convert strings to numbers and then negate them.

let a = 5;
let b = -a;

let c = "8";
let d = -c;

console.log(b); // -5
console.log(d); // -8
            

๐Ÿ” Why Unary Plus is Useful

Without unary plus, adding strings results in concatenation instead of addition.

let num1 = "5";
let num2 = "3";

console.log(num1 + num2);      // "53"
console.log(+num1 + +num2);    // 8
            

๐Ÿงช Try It Yourself

Click the button to see unary operators in action: