4 ms·
I kinda agree that `new URL()` need not bail out when the URL is invalid. Both practices exist in the spec: `new Date('foo')` returns invalid date, `parseInt('f
by qbane 2y ago
I kinda agree that `new URL()` need not bail out when the URL is invalid. Both practices exist in the spec: `new Date('foo')` returns invalid date, `parseInt('foo')` returns NaN, while `new Array(-1)` throws a `RangeError`. Probably there is a need of URL instances for invalid ones? Then we come back at an Either<x, y> return type.
However, it is the `try...catch` pattern that messes up with the `const`, not the URL constructor. It is very annoying every time when I have to wrap an existing block with a try...catch, and inevitably lose the const-ness to some variables, unless I wrap everything again into a function and `return` in the try block if things go normally.
- jakub_g 2y agoRe: try-catch x const, this is indeed one of top annoyances in JS those days. I hope this proposal makes it to the language one day: https://github.com/nzakas/proposal-write-once-const?tab=readme-ov-file#use-case-3-try-catch-initialized-bindings https://github.com/nzakas/proposal-write-once-const?tab=read...
- qbane 2y agoThanks for the reference. I am surprised that Java already has a solution and the choice of keyword "final" is a nice one.
- throwitaway1123 2y agoI often find myself using an immediately invoked function expression to handle the try catch const assignment issue, for example: const result = (() => { try { return new URL(someString) } catch { return null } })() It's not pretty though, and I think the do expressions proposal would rid my codebases of this pattern: https://github.com/tc39/proposal-do-expressions https://github.com/tc39/proposal-do-expressions
- IggleSniggle 2y agoThanks for this, I think your syntax is an improvement over the solutions I've tried
- lucideer 2y agotry/catch messing with const is a well known problem in modern JS & one that imo needs a generalised solution & not one specific to one constructor. As far as other error return patterns existing in "the spec" - there are multiple specs referred to here (ECMA vs DOM) & also multiple eras; there seems to be consensus that some past patterns on error return weren't great decisions & some well considered consensus to move to more broadly accepted known patterns (like try/catch). e.g. for your Date example, that's a really old API that ECMA are working on replacing with Temporal (which throws)