How To Use JavaScript Unary Operators
Mathematically, an operation is a calculation on one or more values called operands mapping to an output value. An operator is a symbol or sign that maps operands to output values.
Unary operators are more efficient than standard JavaScript function calls. Additionally, unary operators can not be overridden, therefore their functionality is guaranteed.
Operator | Explanation |
---|---|
Unary plus (+ ) | Tries to convert the operand into a number |
Unary negation (- ) | Tries to convert the operand into a number and negates after |
Increment (++ ) | Adds one to its operand |
Decrement (-- ) | Decrements by one from its operand |
Logical NOT (! ) | Converts to boolean value then negates it |
Bitwise NOT (~ ) | Inverts all the bits in the operand and returns a number |
typeof | Returns a string which is the type of the operand |
delete | Deletes specific index of an array or specific property of an object |
void | Discards a return value of an expression. |
In this article, you will be introduced to all the unary operators in JavaScript.
Prerequisites
If you would like to follow along with this article, you will need:
- Some familiarity with JavaScript data types, variables, objects, and functions.
Unary plus (+
)
The unary plus operator (
+
) precedes its operand and evaluates to its operand but attempts to convert it into a number if it isn’t already.
It can convert all string representations of numbers, boolean values (true
and false
), and null
to numbers. Numbers will include both integers, floats, hexadecimal, scientific (exponent) notation, and Infinity
.
If the operand cannot be converted into a number, the unary plus operator will return NaN
.
Here are some examples:
Operation | Result |
---|---|
+3 | 3 |
+"3" | 3 |
+"-3" | -3 |
+"3.14" | 3.14 |
+"123e-5" | 0.00123 |
+"0xFF" | 255 |
+true | 1 |
+false | 0 |
+null | 0 |
+"Infinity" | Infinity |
+"not a number" | NaN |
+function(val){ return val } | NaN |
An object can only be converted if it has a key valueOf and its function returns any of the above types.
This will output the following:
Output255
After experimenting with different values, you can continue to the next unary operator.
Unary negation (-
)
The unary negation operator (
-
) precedes its operand and negates it.
Both the unary negation and plus perform the same operation as the Number()
function for non-numbers.
Here are some examples:
Operation | Result |
---|---|
-3 | -3 |
-"3" | -3 |
-"-3" | 3 |
-"3.14" | -3.14 |
-"123e-5" | -0.00123 |
-"0xFF" | -255 |
-true | -1 |
-false | -0 |
-null | -0 |
-"Infinity" | -Infinity |
-"not a number" | -NaN |
-function(val){ return val } | -NaN |
-{ valueOf: function(){ return "0xFF" } } | -255 |
After experimenting with different values, you can continue to the next unary operator.
Increment (++
)
The increment operator (
++
) increments (adds one to) its operand and returns a value.
It can be used as a postfix or prefix operator.
- Postfix: meaning the operator comes after the operand (
y++
). This returns the value before incrementing. - Prefix: the operator comes before the operand (
++y
). Using it as a prefix returns the value after incrementing.
Here is a postfix example:
y
is set to the value before incrementing and it adds 1
to x
.
Be careful about resetting values when using postfix:
z
is set to the value before incrementing.
Here is a prefix example:
y
is set to the value after incrementing and it adds 1 to x
.
z
is set to the value after incrementing.
After experimenting with different values, you can continue to the next unary operator.
Decrement (--
)
The decrement operator (
--
) decrements (subtracts one from) its operand and returns a value.
It can be used as a postfix or prefix operator.
- Postfix: meaning the operator comes after the operand (
y--
). This returns the value before decrementing. - Prefix: the operator comes before the operand (
--y
). Using it as a prefix returns the value after decrementing.
Here is a postfix example:
Sets y
to the value before decrementing and it removes 1 from x
.
z
is set to the value before decrementing.
Here is a prefix example:
Sets y
to the value after decrementing and it removes 1 from x
.
z
is set to the value after decrementing.
After experimenting with different values, you can continue to the next unary operator.
Logical NOT (!
)
The logical NOT (
!
) operator (logical complement, negation) takes truth to falsity and vice versa.
Here are some examples:
Operation | Result |
---|---|
!false | true |
!NaN | true |
!0 | true |
!null | true |
!undefined | true |
!"" | true |
!true | false |
!-3 | false |
!"-3" | false |
!42 | false |
!"42" | false |
!"string" | false |
!"true" | false |
!"false" | false |
!{} | false |
![] | false |
!function(){} | false |
These examples demonstrate how logical NOT returns false
if the operand can be converted to true
, if not it returns false
.
You can also use double negation (!!
).
Let’s examine the last example.
First, a negation of a string returns false
:
Then, a negation of false
, returns true
:
Thus:
After experimenting with different values, you can continue to the next unary operator.
Bitwise NOT (~
)
The bitwise NOT operator (
~
) inverts the bits of its operand.
A bitwise not on a number results in: -(x + 1)
.
a | NOT a |
---|---|
0 | 1 |
1 | 0 |
Here are some examples:
Operation | Result |
---|---|
~3 | -4 |
~"3" | -4 |
~"-3" | 2 |
~"3.14" | -4 |
~"123e-5" | -1 |
~"0xFF" | -256 |
~true | -2 |
~false | -1 |
~null | -1 |
~"Infinity" | -1 |
~"not a number" | -1 |
~function(val){ return val } | -1 |
~{ valueOf: function(){ return "0xFF" } } | -256 |
The table below takes a deeper look into how this operation is performed.
(base 10) | (base 2) | NOT (base 2) | NOT (base 10) |
---|---|---|---|
2 | 00000010 | 11111101 | -3 |
1 | 00000001 | 11111110 | -2 |
0 | 00000000 | 11111111 | -1 |
-1 | 11111111 | 00000000 | 0 |
-2 | 11111110 | 00000001 | 1 |
-3 | 11111101 | 00000010 | 2 |
After experimenting with different values, you can continue to the next unary operator.
typeof
The
typeof
operator returns a string indicating the type of the unevaluated operand.
Here are some examples:
Operation | Result |
---|---|
typeof 3 | 'number' |
typeof '3' | 'string' |
typeof -3 | 'number' |
typeof 3.14 | 'number' |
typeof 123e-5 | 'number' |
typeof 0xFF | 'number' |
typeof true | 'boolean' |
typeof false | 'boolean' |
typof null | 'object' |
typeof Infinity | 'number' |
typeof NaN | 'number' |
typeof function(val){ return val } | 'function' |
typeof { valueOf: function(){ return '0xFF' } } | object |
typeof [1,2,3] | 'object' |
typeof {hi: "world"} | 'object' |
typeof Date() | 'string' |
typeof new Date() | 'object' |
typeof undefined | 'undefined' |
After experimenting with different values, you can continue to the next unary operator.
delete
The JavaScript
delete
operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.
It returns true
if it successfully deleted the property or if the property does not exist.
It returns false
if it fails to delete an item.
delete
does not have any effect on both functions and variables.
Here is an example of attempting to use delete
on a variable:
Here is an example of attempting to use delete
on a function:
Here is an example of attempting to use delete
on an array:
Here is an example of attempting to use delete
on an object:
Now, here is an example of using delete
on a property with the literal notation:
And here is an example of using delete
on a property with the dot notation:
Here is an example of attempting to use delete
on a property that does not exist:
Here is an example of attempting to use delete
on a non-configurable property of a predefined object:
delete
has no effect on an object property that is set as non-configurable. It will always return false
.
In strict mode, this will raise a SyntaxError
.
Here is an example of attempting to use delete
on a non-configurable property:
Here is an example of using delete
on a non-configurable property:
Read more about defineProperty()
.
var
, let
, and const
create non-configurable properties that cannot be deleted with the delete
operator:
Here is an example of setting up a var
in a window
scope (e.g., a web browser):
This will return:
Then attempting to delete
the variable:
This will return:
Here is an example of setting up a var
in a global
scope (e.g., Node):
This will return:
Now, here is an example of an Object:
This will return:
Notice that the configurable
property is marked as true
.
Arrays
are considered type Object
in JavaScript. Thus this method will work on them:
The delete
operator will only delete the value and not the index of the array. It will leave the value of that particular index as undefined
. This is why the length does not change.
In strict
mode, delete
throws a SyntaxError
due to the use of a direct reference to a variable, a function argument, or a function name.
Here is an example of a direct reference to a variable that will cause a SyntaxError
:
This will produce:
OutputUncaught SyntaxError: Delete of an unqualified identifier in strict mode.
Here is an example of a function argument that will cause a SyntaxError
:
Here is an example of a function name that will cause a SyntaxError
:
Here are a few pointers to always consider when using delete
:
- Trying to delete a property that does not exist,
delete
will returntrue
but will not have an effect on the object. - Delete only affects an object’s own properties. This means if a property with the same name exists on the object’s prototype chain, then
delete
will not affect it. After deletion, the object will use the property from the prototype chain. - Variable declared
var
,let
, andconst
cannot be deleted from the global scope or from a function’s scope.- Meaning:
delete
cannot delete any functions in the global scope or in the function scope. delete
works on functions that are part of an object (apart from the global scope).
- Meaning:
- Non-configurable properties cannot be removed.
delete
does not work on any of the built-in objects likeMath
,Array
,Object
or properties that are created as non-configurable with methods likeObject.defineProperty()
.
After experimenting with different values, you can continue to the next unary operator.
void
The
void
operator evaluates the given expression and then returnsundefined
.
void
operator’s main purpose is to return undefined
. The void operator specifies an expression to be evaluated without returning a value.
The void operator is used in either of the following ways: void (expression)
or void expression
.
Note: The void
operator is not a function, so ()
are not required, but it is a good style to use them according to MDN
Here is an example:
This will return:
Here is an example of a function:
If you reference the function:
This will return the value 4
:
However, if you void
the function:
This will return the value undefined
:
The void
operator can also be used to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.
Here is an example of using void(0)
on a link:
The code above creates a link that does nothing when a user clicks it. This is because void(0)
evaluates to undefined
.
Here is an example of using void(document.form.submit())
on a link:
The code creates a link that submits a form when the user clicks it.
Experiment with different values.
Conclusion
In this article, you were introduced to all the unary operators in JavaScript.
Always consider the order of operations when dealing with more than one operator. This is good practice in mitigating unforeseen bugs.
Here is a brief table that shows the order of precedence in operations when using Javascript. Operands on the same level have the same order of precedence.
Operator type | Operators | Example |
---|---|---|
member | . [] | [1,2,3] |
call / create instance | () new | var vehicle = new Vehicle(); |
negation / increment | ! ~ + - ++ -- typeof void delete | typeof [1,2,3] |
multiply / divide | * / % | 3 % 3 |
addition / subtraction | + - | 3 + 3 |
bitwise shift | << >> >>> | 9 << 2 |
relational | < <= > >= in instanceof | [1] instanceof Array |
equality | == != === !== | void(0) === undefined |
bitwise-and | & | 5 & 1 |
bitwise-xor | ^ | 5 ^ 1 |
bitwise-or | | | 5 | 1 |
logical-and | && | x < 10 && y > 1 |
logical-or | || | x == 5 || y == 5 |
conditional | ?: | (amount < 10) ? "Few" : "Many" |
assignment | = += -= *= = %= <<= >>= >>>= &= ^= |= | x = 8 |
comma | , | b = 3, c = 4 |
If you’d like to learn more about JavaScript, check out our JavaScript topic page for exercises and programming projects.