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




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: