The Mystery of the Plus Sign in JavaScript Date Handling
In JavaScript, the plus ( ) sign is often used in conjunction with other operators to perform various operations. However, its usage with the new Date expression may be particularly confusing.
Consider the following code snippet:
<code class="javascript">function fn() { return +new Date; }</code>
What does the plus sign do in this context? Why does it return a timestamp instead of a date object?
Unary Operator: Converting to Numeric
The plus sign here acts as a unary operator. It converts the result of the new Date expression into a numeric value. The Date object represents a date and time, and the unary plus operator implicitly calls the valueOf method on this object to obtain the numeric timestamp representing the number of milliseconds since the Unix epoch (January 1, 1970 00:00:00 UTC).
Equivalent Code
The code snippet above is equivalent to the following more explicit expression:
<code class="javascript">function() { return Number(new Date); }</code>
The Number function explicitly converts the Date object to a numeric value, achieving the same result as the unary plus operator.
Conclusion
The plus sign in the new Date expression is a unary operator that coerces the Date object into a numeric timestamp. This is documented in the Mozilla Developer Network (MDN) reference on unary operators (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus) and illustrated in the famous XKCD comic on unary addition (https://xkr.us/articles/javascript/unary-add).
The above is the detailed content of What is the Purpose of the Plus Sign in JavaScript Date Handling?. For more information, please follow other related articles on the PHP Chinese website!