Unary plus operator in JavaScript

The unary plus (+) operator is a unary operator and converts its operand to a number, if it isn’t already. It is equivalent to the Number() constructor called as a function. Let us see some examples of the Unary + operator and what does it imply in different scenarios

+new Date; // implies Number(new Date)
a + “” // implies String(a)
+a // implies Number(a), so “+1.2” becomes 1.2
a = null; a = +a; // value of a is now 0;
Unary plus is the preferred way of converting something into a number!

Note: The unary plus operator does not change the sign of an integer. So if the number is  negative, the unary + does not change the sign to a positive

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: