JavaScript Unary operators
Unary operators in JavaScript operate on a single operand and perform various operations, such as negation, type conversion, and incrementing or decrementing values. Here’s a breakdown of the main unary operators:
1. Unary Plus (+
)
Purpose: Converts a value to a number. It’s often used to force a value to be numeric.
Example:
let str = '5'; let num = +str; // num is 5 (number)
let bool = true; let num = +bool; // num is 1 (true is coerced to 1)
2. Unary Minus (-
)
Purpose: Negates a value. It converts a value to a number and then changes its sign.
Example:
let a = 5; let neg = -a; // neg is -5
let str = '10'; let num = -str; // num is -10 (string '10' is coerced to number)
3. Logical NOT (!
)
Purpose: Inverts the boolean value of its operand. If the operand is
true
, it returnsfalse
; if it’sfalse
, it returnstrue
.Example:
let a = true; let notA = !a; // notA is false
let b = 0; let notB = !b; // notB is true (0 is falsy)
4. Increment (++
)
- Purpose: Increases the value of a variable by 1. It can be used as a prefix or postfix operator.
- Prefix (
++x
): Increments the value before using it in an expression. - Postfix (
x++
): Uses the value before incrementing it.
- Prefix (
- Example:
let a = 5; console.log(++a); // 6 (a is incremented before being used) let b = 5; console.log(b++); // 5 (b is used before being incremented) console.log(b); // 6 (b is incremented after the first use)
5. Decrement (--
)
- Purpose: Decreases the value of a variable by 1. It can be used as a prefix or postfix operator.
- Prefix (
--x
): Decrements the value before using it in an expression. - Postfix (
x--
): Uses the value before decrementing it.
- Prefix (
- Example:
let a = 5; console.log(--a); // 4 (a is decremented before being used) let b = 5; console.log(b--); // 5 (b is used before being decremented) console.log(b); // 4 (b is decremented after the first use)
6. Typeof Operator (typeof
)
- Purpose: Returns a string indicating the type of the operand.
- Example:
let a = 42; console.log(typeof a); // 'number' let b = 'Hello'; console.log(typeof b); // 'string'
7. Instanceof Operator (instanceof
)
- Purpose: Tests whether an object is an instance of a particular constructor or class.
- Example:
let arr = [1, 2, 3]; console.log(arr instanceof Array); // true let date = new Date(); console.log(date instanceof Date); // true
Key Points:
- Type Coercion: Unary operators like
+
and-
can coerce values to numbers, which can be useful for type conversions. - Short-circuiting: The
!
operator can be used for simple boolean inversion and is also useful in conditional expressions. - Increment/Decrement:
++
and--
operators affect the value of a variable and can be used in expressions to alter their value based on whether they are prefix or postfix.