JavaScript Unary + Operator

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 to NaN. 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:

sorcery-witchcraft-javascript

JavaScript Unary Add →
x vs. parseInt(x) vs. parseFloat(x) vs. Number(x) vs. +x vs. ~~x vs. x>>>0

(via a tweet by @flurin)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.