1

I've recently come across this intriguing line of code:

var date = +new Date;

console.log(date);

So I experimented with putting + before strings to better understand what was going on and this was the result:

var one = +"1"; // -> 1
var negativeTwo = -"2"; // -> -2
var notReallyANumber = +"number: 1"; // -> NaN

console.log(one, negativeTwo, notReallyANumber);

It seems that whenever a + sign or a - sign is placed before a string, it converts that string into a number, and if a negative sign is placed before a string, the resulting number will be negative.

Finally, if the string is not numeric, the result will be NaN.

Why is that?

How does putting + or - signs before a string convert it into a number and how does it also apply to new Date?

EDIT:

How does a + sign affect new Date? How does the value Wed Nov 07 2018 21:50:30 GMT-0500 for example, convert into a numerical representation?

Mystical
  • 2,505
  • 2
  • 24
  • 43
  • 4
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_() – Daniel A. White Nov 08 '18 at 02:45
  • @CertainPerformance the question has been edited and is no longer a duplicate. – Mystical Nov 08 '18 at 02:57
  • In JavaScript, each `Object` has a `valueOf()` method. Putting `+` in front of an Object calls that method on it, and `Date` overrides it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf (also, `+new Date` is a syntax error, but JS is lenient and turns that into `+new Date()`) –  Nov 08 '18 at 03:05

1 Answers1

1

+ converts the following expression into a number, if it can. If the following expression is an object, then that object's valueOf function is called, so as to returns the primitive value of the specified object, which can then be (attempted) to be coerced to a number.

How does a + sign affect new Date? How does the value Wed Nov 07 2018 21:50:30 GMT-0500 for example, convert into a numerical representation?

Date.prototype.valueOf returns the integer timestamp of the date object in question:

console.log(
  new Date().valueOf()
);

And this method is indeed called when + is before a Date object, as you can see here (just for demonstration, this shouldn't be in real code):

Date.prototype.valueOf = () => 5;
console.log(+new Date());

So, the Date object is converted to a number via valueOf. (This is before the + coerce-to-number operation has actually occurred, but since it's already a number, it doesn't affect anything further)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320