While browsing through this answer regarding the Hidden Features of JavaScript?, I came across a perplexing behavior:
> new Date
< Fri Feb 26 2016 21:15:43 GMT-0500 (EST)
> +new Date
< 1456539382581
< 0 + new Date + 0
"0Fri Feb 26 2016 21:17:39 GMT-0500 (EST)0"
I was astonished to discover that the Date constructor returns an object which, when converted to a number via unary operation (but not addition), yields a number representing the Unix Epoch.
This raises the question: How is this possible? After researching the topic, it appears that JavaScript lacks support for operator overloading, or only offers limited overloading of non-operator functions like add
and toString
.
Considering JS doesn't appear to have a specific function for unary + (or any number coercion mechanism at all), how exactly does this functionality work?