Cast to Number in Javascript using the Unary (+) Operator

The Unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number

Unary plus (+)

Unary operators work on single operands. The Unary (+) operator is no different, and it precedes it’s operand.

var positiveOne = +1
+false  // 0
+‘123’ // 123
+0xBABE // 47806 (Hexadecimal)
+null // 0
+function(val) {return val } // NaN
+''     // NaN
+'123a' // NaN
+{} // NaN
Image for post
Image for post
Javascript Number conversions

Written by

Tips and tricks on Travelling and Web Engineering because I’m a Travelling Web Engineer!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store