5 ms·
That article is wrong. A date can definitely be serialized in JS. It is in fact converted to a ISO string when it is transformed into JSON, but the article says
by simlevesque 8y ago
That article is wrong. A date can definitely be serialized in JS. It is in fact converted to a ISO string when it is transformed into JSON, but the article says it does not. The author needs to learn about JSON.stringify and the toJSON method of built-ins.
- deleted 8y ago[deleted]
- fendrak 8y agoIndeed it can, but I believe the point is that it's not round-tripable, meaning you can't parse the resulting serialized JSON back into its original form, the one that contained the Date objects. If you could do so, JSON.stringify/parse would be a convenient way to do a deep clone.
- simlevesque 8y agoYeah that's right. All I'm saying is that no matter what, the following sentence is false: > An example of a non-serializable value type is the Date object - it is printed in a non ISO-standard format and cannot be parsed back to its original value :(.
- zachrose 8y agoIt would be cool if there was a webpage for “Is your function ______?” with a list of things that functions can be: - Roundtrip-able (reversible?) - Pure - Effectful - Mutation-doing - Idempotent/Nullipotent - Algebraically closed over the set of its inputs - Et c. Every time I hear about a new one I wish I had such a list
- deleted 8y ago[deleted]
- wheresvic1 8y agoAha yes you are correct - it outputs an ISO string at the very least but does not parse it back to a date. I will update the article to reflect this!
- simlevesque 8y agoOk but please read carefuly because JSON.parse can in fact recover dates. The JSON.parse function accepts a 'reviver' function as an argument to do just that. 99% of the time it's not useful so there is no reason for JSON.parse to do it by default but JSON.parse definitely can parse dates back if you use all it's features. I like that it does not do it by default but I can make it parse the dates if I want.
- Spivak 8y agoSaying that JSON.parse can do something when it's really just you implementing the transformation from string to date object is a little misleading. You can make JSON parse arbitrary sublanguages if you're willing to put in the work.
- dzek69 8y agoThat way you can get different result, as you could actually have date object and date as string stored somewhere. You will need custom strigify callback to differentiate which should be converted back to date on parse and which should be a string. Still, this is not pure json this way, it's your own transformations
- switch007 8y agoAnd what do you pass as the reviver argument? Your own function to check a string to see if it's valid IS8601 and parse it? That's just using parse()'s recursive walking of the object: it does no date reviving itself, right?