In JavaScript, a unary operator is an operator that works on a single operand. These operators are concise shortcuts for performing various operations like incrementing or decrementing a number, or converting a value to a number. Understanding how they work, especially the difference between prefix and postfix, is fundamental for any JavaScript developer.
Example 1: Increment Operator (++)
// Example of the postfix increment operator
let score = 10;
// The original value of 'score' (10) is assigned to 'newScore' first
// Then, 'score' is incremented to 11
let newScore = score++;
console.log(`newScore: ${newScore}`); // Output: newScore: 10
console.log(`score: ${score}`); // Output: score: 11
Explanation
The postfix increment operator (++
after the operand) first returns the original value of the variable and then increases the variable's value by one. In this case, newScore
is assigned the value of score
before score
is incremented.
Example 2: Decrement Operator (--)
// Example of the prefix decrement operator
let lives = 5;
// 'lives' is first decremented to 4
// Then, the new value of 'lives' (4) is assigned to 'remainingLives'
let remainingLives = --lives;
console.log(`remainingLives: ${remainingLives}`); // Output: remainingLives: 4
console.log(`lives: ${lives}`); // Output: lives: 4
Explanation
The prefix decrement operator (--
before the operand) first decreases the variable's value by one and then returns the new, decremented value. Here, lives
is decremented to 4, and that new value is then assigned to remainingLives
.
Example 3: Unary Plus (+)
// Example of the unary plus for type conversion
let stringValue = "25";
// The unary plus operator converts the string "25" into the number 25
let numericValue = +stringValue;
console.log(typeof stringValue); // Output: string
console.log(typeof numericValue); // Output: number
console.log(numericValue + 5); // Output: 30
Explanation
The unary plus operator (+
) is the fastest way to convert a string or other data type into a number if that value is a valid numerical representation. It does not perform any mathematical operation but instead focuses solely on type conversion. This is a common and efficient trick used in modern JavaScript.
Example 4: Unary Minus (-)
// Example of the unary minus operator
let positiveNumber = 50;
// The unary minus operator negates the value of the operand
let negativeNumber = -positiveNumber;
console.log(negativeNumber); // Output: -50
let alreadyNegative = -20;
// Applying unary minus to a negative number makes it positive
console.log(-alreadyNegative); // Output: 20
Explanation
The unary minus operator (-
) negates its operand, converting a positive number to its negative equivalent or a negative number to its positive equivalent. It also attempts to convert non-numeric operands into a number before negating it, similar to the unary plus.