Understanding Unary Operators in JavaScript
Let's explore how unary operators behave in JavaScript using the following examples:
+true;
!'Lydia';
What do you think the result of each expression would be?
1. +true;
: The unary plus operator (+
) attempts to convert its operand to a number. Since true
has a boolean value of true
, it converts to the number 1
. So, the result would be 1
.
2. !'Lydia';
: The logical NOT operator (!
) negates its operand. In JavaScript, empty strings are falsy values, so 'Lydia'
is a truthy value. Therefore, the logical NOT of a truthy value is false
. So, the result would be false
.
These examples demonstrate how unary operators can be used to perform type conversion and logical operations in JavaScript.