Unary operators act on a single operand to perform operations like type conversion, value manipulation, or checking certain conditions. Let’s look at some common unary operators and how they work.
The unary plus operator converts its operand into a number. If the operand is already a number, it remains unchanged.
const str = '42';
const strToNum = +str;
console.log(strToNum); // 42
console.log(typeof str); // string
console.log(typeof strToNum); // number
Unary plus is handy when you want to make sure you’re working with a numeric value. As you might guess, there’s a unary negation operator. It negates the value of the operand. It works similarly to the unary plus, except it flips the sign.
const str = '42';
const strToNegativeNum = -str;
console.log(strToNegativeNum); // -42
console.log(typeof str); // string
console.log(typeof strToNegativeNum); // number
The logical NOT operator, represented by an exclamation mark (!
), is another unary operator. It flips the boolean value of its operand. So, if the operand is true
, it becomes false
, and if it’s false
, it becomes true
.
let isOnline = true;
console.log(!isOnline); // false
let isOffline = false;
console.log(!isOffline); // true
The bitwise NOT operator is a less commonly used unary operator. Represented by a tilde, ~
, it inverts the binary representation of a number. Computers store numbers in binary format (1s and 0s). The ~
operator flips every bit, meaning it changes all 1s to 0s and all 0s to 1s. You will learn more about binary and bits in a future lecture video.
const num = 5; // The binary for 5 is 00000101
console.log(~num); // -6
In this example, 5
became -6
because by applying the ~
operator to 5
, you get - (5 + 1)
, which equals -6
due to two’s complement representation. Two’s complement is a way computers represent negative numbers in binary. You probably won’t use the bitwise NOT often unless you’re working with low-level programming tasks like manipulating bits directly.
The void
keyword is a unary operator that evaluates an expression and returns undefined
.
const result = void (2 + 2);
console.log(result); // undefined
void
is also commonly used in hyperlinks to prevent navigation:
<a href="javascript:void(0);">Click Me</a>
Finally, there is the typeof
operator which you learned about in previous lecture videos. This returns the type of its operand as a string.
const value = 'Hello world';
console.log(typeof value); // string