11+ Year IT Industry Experience, Working as Technical Lead with Capgemini | Consultant | Leadership and Corporate Trainer | Motivational and Technical Speaker | Career Coach | Author | MVP | Founder Of RVS Group | Trained more than 4000+ IT professionals | Azure | DevOps | ASP.NET | C# | MVC | WEB API | ANGULAR | TYPESCRIPT | MEAN | SQL | SSRS | WEB SERVICE | WCF... https://bikeshsrivastava.blogspot.in/ http://bikeshsrivastava.com/
Monday, December 26, 2022

Trending Top 10 Project Management Tools

 Now we have lot of project of management tools in market, but here I am listing top 10 project which are trending.

  • Azure DevOps
  • Jira Software
  • Microsoft Project
  • Excel
  • Basecamp
  • Asana
  • Trello
  • ProofHub
  • Wrike
  • LiquidPlanner
  • Clarizen
  • Quire
  • Zoho Projects
  • ProjectManager
  • Mavenlink
  • ActiveCollab
  • Avaza
  • Teamwork
  • Workzone
  • Paymo
  • Monday.com
  • Clickup
Bikesh Srivastava Project Management
Wednesday, November 23, 2022

Do you know about JavaScript Unary Operators?

 How To Use JavaScript Unary Operators

Introduction

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.

A unary operation is an operation with only one operand. This operand comes either before or after the operator.

Unary operators are more efficient than standard JavaScript function calls. Additionally, unary operators can not be overridden, therefore their functionality is guaranteed.

OperatorExplanation
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
typeofReturns a string which is the type of the operand
deleteDeletes specific index of an array or specific property of an object
voidDiscards 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, variablesobjects, 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:

OperationResult
+33
+"3"3
+"-3"-3
+"3.14"3.14
+"123e-5"0.00123
+"0xFF"255
+true1
+false0
+null0
+"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.

+{
  valueOf: function() {
    return "0xFF"
  }
}

This will output the following:

Output
255

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:

OperationResult
-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:

x = 4       // x = 4
y = x++     // y = 4 and  x = 5

y is set to the value before incrementing and it adds 1 to x.

Be careful about resetting values when using postfix:

var z = 5   // z = 5
z = z++     // z = 5

z is set to the value before incrementing.

Here is a prefix example:

x = 4       // x = 4
y = ++x     // y = 5 and  x = 5

y is set to the value after incrementing and it adds 1 to x.

var z = 5   // z = 5
z = ++z     // z = 6

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:

x = 4       // x = 4
y = x--     // y = 4 and  x = 3

Sets y to the value before decrementing and it removes 1 from x.

var z = 5   // z = 5
z = z--     // z = 5

z is set to the value before decrementing.

Here is a prefix example:

x = 4       // x = 4
y = --x     // y = 3 and  x = 3

Sets y to the value after decrementing and it removes 1 from x.

var z = 5   // z = 5
z = --z     // z = 4

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:

OperationResult
!falsetrue
!NaNtrue
!0true
!nulltrue
!undefinedtrue
!""true
!truefalse
!-3false
!"-3"false
!42false
!"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 (!!).

!!1 === true        // returns true
!!0 === false       // returns true
!!'hi' === true     // returns true

Let’s examine the last example.

First, a negation of a string returns false:

!'hi'               // returns false

Then, a negation of false, returns true:

!false              // returns true

Thus:

true === true       // returns true

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).

aNOT a
01
10

Here are some examples:

OperationResult
~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)
20000001011111101-3
10000000111111110-2
00000000011111111-1
-111111111000000000
-211111110000000011
-311111101000000102

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:

OperationResult
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:

var variableExample = 1;
delete variableExample;          // returns false
console.log(variableExample);    // returns 1

Here is an example of attempting to use delete on a function:

function functionExample(){};
delete functionExample;           // returns false
console.log(functionExample);     // returns function functionExample(){}

Here is an example of attempting to use delete on an array:

var arrayExample = [1,1,2,3,5]
delete arrayExample             // returns false
console.log(arrayExample);      // [1,1,2,3,5]

Here is an example of attempting to use delete on an object:

var objectExample = {propertyExample: "1"}
delete objectExample            // returns false
console.log(objectExample);     // returns Object { propertyExample: "1" }

Now, here is an example of using delete on a property with the literal notation:

var inventory = {"apples": 1, "oranges": 2}
delete inventory["apples"]          // returns true
console.log(inventory);             // returns Object { "oranges": 2 }
console.log(inventory["apples"]);   // returns undefined

And here is an example of using delete on a property with the dot notation:

var inventory = {"apples": 1}
delete inventory.apples;            // returns true
console.log(inventory);             // returns {}
console.log(inventory.apples);      // returns undefined

Here is an example of attempting to use delete on a property that does not exist:

var inventory = {"apples": 1};
delete inventory.oranges;           // returns true
console.log(inventory.apples);      // returns 1

Here is an example of attempting to use delete on a non-configurable property of a predefined object:

delete Math.PI;                     // returns false
console.log(Math.PI);               // returns 3.141592653589793

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:

var configurableFalseExample = {};
Object.defineProperty(configurableFalseExample, 'name', { value: 'Sammy', configurable: false })
console.log(configurableFalseExample.name);     // returns 'Sammy'
delete configurableFalseExample.name            // returns false
console.log(configurableFalseExample.name);     // returns 'Sammy'

Here is an example of using delete on a non-configurable property:

var configurableTrueExample = {};
Object.defineProperty(configurableTrueExample, 'name', { value: 'Sammy', configurable: true })
console.log(configurableTrueExample.name);      // returns 'Sammy'
delete configurableTrueExample.name             // returns true
console.log(configurableTrueExample.name);      // returns undefined

Read more about defineProperty().

varlet, 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):

var num = 1;
Object.getOwnPropertyDescriptor(window, "num")

This will return:

Output
{ value: 1, writable: true, enumerable: true, configurable: false }

Then attempting to delete the variable:

delete num;

This will return:

Output
false

Here is an example of setting up a var in a global scope (e.g., Node):

var num = 1;
Object.getOwnPropertyDescriptor(global, "num")

This will return:

Output
{ value: 1, writable: true, enumerable: true, configurable: false }

Now, here is an example of an Object:

var inventory = { "apples": 1 };
Object.getOwnPropertyDescriptor(inventory, "apples")

This will return:

Output
{ value: 1, writable: true, enumerable: true, configurable: true }

Notice that the configurable property is marked as true.

Arrays are considered type Object in JavaScript. Thus this method will work on them:

var arrayExample = [20,30,40];
console.log(arrayExample.length);     // returns 3
delete arrayExample[2]                // returns true
console.log(arrayExample);            // returns [ 20, 30, <1 empty item> ]
console.log(arrayExample[2]);         // returns undefined
console.log(arrayExample.length);     // returns 3

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:

‘use strict’
var inventory = {"apples": 1, "oranges": 2};
delete inventory;

This will produce:

Output
Uncaught SyntaxError: Delete of an unqualified identifier in strict mode.

Here is an example of a function argument that will cause a SyntaxError:

‘use strict’
function Person() {
 delete name;
 var name;
}

Here is an example of a function name that will cause a SyntaxError:

‘use strict’
function yo() { }

delete yo;

Here are a few pointers to always consider when using delete:

  • Trying to delete a property that does not exist, delete will return true 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 varlet, and const 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).
  • Non-configurable properties cannot be removed.
  • delete does not work on any of the built-in objects like MathArrayObject or properties that are created as non-configurable with methods like Object.defineProperty().

After experimenting with different values, you can continue to the next unary operator.

void

The void operator evaluates the given expression and then returns undefined.

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:

void 0

This will return:

Output
undefined

Here is an example of a function:

var functionExample = function () {
  console.log('Example')
  return 4;
}

If you reference the function:

var result = functionExample()
console.log(result);

This will return the value 4:

Output
4

However, if you void the function:

var voidResult = void (functionExample())
console.log(voidResult);

This will return the value undefined:

Output
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:

<a href="javascript:void(0)">Link to perform no action.</a>

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:

<a href="javascript:void(document.form.submit())">Link to submit a form.</a>

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 typeOperatorsExample
member. [][1,2,3]
call / create instance() newvar vehicle = new Vehicle();
negation / increment! ~ + - ++ -- typeof void deletetypeof [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.

Life Is Complicated, But Now programmer Can Keep It Simple.