Today I learned:
In JavaScript it is possible to use the
+
operator alone before a single element. This indicates a math operation and tries to convert the element to a number. If the conversion fails, it will evaluate toNaN
. This is especially useful when one wants to convert a string to a number quickly, but can also be used on a select set of other types.
For example, the snippet below will return a timestamp, instead of a Date
:
function fn() {
return +new Date;
}
That’s because it is the equivalent of this snippet:
function fn() {
return Number(new Date);
}
So, is there a difference between parseInt()
and the unary +
operator then, one might wonder? Here’s a handy overview:
JavaScript Unary Add →
x
vs. parseInt(x)
vs. parseFloat(x)
vs. Number(x)
vs. +x
vs. ~~x
vs. x>>>0
→