Why does adding a date result in a string?

I am trying to understand this behavior:

var d = new Date(); console.log(+d); // 1458049171381 console.log(1 + d); // '1Tue Mar 15 2016 09:39:31 GMT-0400 (EDT)' 

Unlike:

 var obj = { valueOf: function () { return 123; } }; console.log(+obj); // 123 console.log(1 + obj); // 124 

Why is the result of adding Date to string when Date.prototype.valueOf returns number ?

Here is the naive translation specification of the add operator in JavaScript

 function ToPrimitive(x) { return x.valueOf(); } function IsString(x) { return typeof x === 'string'; } function ToString(x) { return x.toString(); } function ToNumber(x) { try { return parseFloat(x); } catch (e) { return NaN; } } function AdditionOperator(lval, rval) { let lprim = ToPrimitive(lval); let rprim = ToPrimitive(rval); if (IsString(lprim) || IsString(rprim)) { return ToString(lprim) + ToString(rprim); } else { return ToNumber(lprim) + ToNumber(rprim); } } 

However, if I call this with a Date object, it returns a numeric value:

 AdditionOperator(new Date(), 1) // 1458049347088 

Can someone shed some light on this?

+5
source share
1 answer

Walk-through:

  • Before adding, both the left and right values ​​of the binary operation are converted to primitives ( string or number ).

  • Depending on the context of the value, a β€œhint” may be provided that tells what primitive type it should become.

  • If no hint is specified, its preferred type will be selected by default. All Object have the preferred type number , with the exception of Date , which prefers string (and confuses everyone).

According to spec

All standard objects except Date objects handle the absence of a hint as if the hint number was specified; Date objects handle the absence of a hint as if a string was specified. Exotic objects can handle the absence of a hint in another way.

And in the case of Date, they make an exception

Of the objects defined in this specification, only Date (see 20.3.4.45) and Symbol (see Section 19.4.3.4) objects, override the default behavior. Date objects do not refer to hints, as if the hint was a String.

Also check this

This function is called by ECMAScript operators to convert a Date object to a primitive value. Valid values ​​for the prompt are: "default", "number" and "string". Date objects are unique among the built-in ECMAScript object in the sense that they treat the "default value" as the equivalent of "string", all other built-in ECMAScript objects treat "default" as the equivalent of "number".

So, Date is only used as a string.

+4
source

Source: https://habr.com/ru/post/1245092/


All Articles