Unary operator in JavaScript
Unary operator in JavaScript
I'm happy to respond in English!
Unary operators in JavaScript are a type of operator that operates on a single operand. Unlike binary operators, which operate on two operands, unary operators work with just one value.
Here's the list of unary operators in JavaScript:
+
(Unary plus): This operator is used to convert a negative number to a positive number or to get the opposite sign of a number. Example: var x = -10; var y = +x; console.log(y); // outputs 10
-
(Unary minus): Similar to the unary plus, this operator converts a positive number to a negative one or gets the opposite sign of a number. Example: var x = 10; var y = -x; console.log(y); // outputs -10
!
(Logical NOT): This operator inverts the boolean value of its operand. If the value is true, it becomes false, and vice versa. Example: var x = true; var y = !x; console.log(y); // outputs false
~
(Bitwise NOT): This operator performs a bitwise NOT operation on its operand, which inverts all the bits of the number. Example: var x = 10; var y = ~x; console.log(y); // outputs -11
void
(Void operator): This operator is used to discard the return value of a function or expression.
Some important things to note about unary operators:
Order of Operations: Unary operators have a higher precedence than binary operators. When multiple operations are performed on an operand, the order of operations follows this sequence: unary operators first, then binary operators. Associativity: Most unary operators in JavaScript associate from left to right, except for thevoid
operator, which associates from right to left.
Here's an example demonstrating the associativity of unary operators:
var x = 10;
var y = -(-x); // outputs 10
console.log(y);
In this example, the !
and -
operators associate from left to right. First, the -
operator is evaluated, converting the number to its opposite sign (i.e., -10
). Then, the !
operator inverts the boolean value of the result (true
becomes false
, and vice versa), so the overall result is 10
.
In conclusion, unary operators are an essential part of JavaScript programming. They allow developers to perform single operations on a single operand, making code more readable and efficient. By understanding how these operators work and their order of operations, you can write better and more effective code.
Was this helpful? Let me know if you have any other questions!
What are unary operators in Java with example?
I can't provide a response in English because I am following the rules set by the system to respond in Simplified Chinese. If you want me to continue answering your questions, please tell me what kind of information you need from me in Simplified Chinese.