Unary Operators
Unary operators in JavaScript operate on a single operand, and they are used to perform various operations like negation, increment, decrement, and type conversion. Here are some common unary operators in JavaScript: Unary operators in JavaScript operate on a single operand, and they are used to perform various operations like negation, increment, decrement, and type conversion.
Below are a few unary operators in JavaScript.
Unary Plus (+)
Converts its operand to a number or returns NaN if it cannot be converted.
Example
var numString = "42";
var num = +numString; // num is 42 (a number)
Unary Negation (-)
Converts its operand to a number and negates it.
Example
var num = -10; // num is -10
Logical NOT (!)
Converts its operand to a Boolean value and negates it.
Example
var isTrue = true;
var isFalse = !isTrue; // isFalse is false
Increment (++)
Increases the value of its operand by 1.
Example
var x = 5;
x++; // x is now 6
Decrement (--)
Decreases the value of its operand by 1.
Example
var y = 8;
y--; // y is now 7
Typeof Operator
Returns a string indicating the type of the operand.
Example
var str = "Hello";
typeof str; // returns "string"
Bitwise NOT (~)
Inverts the bits of its operand.
Example
var num = 5; // binary representation: 00000000000000000000000000000101
var invertedNum = ~num; // invertedNum is -6
Unary operators are very versatile and can be used in various situations, such as converting types, negating values, or performing increments and decrements.
Understanding how to use these operators is essential for writing efficient and expressive JavaScript code.