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)

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

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.