Create empty URL object from scratch in JavaScript

You have already figured out the workaround and there is no alternative other than passing the parts in or starting with a URL and mutating it.

I'll try to answer:

What caused such design decision in the first place?

By far the most common use case for URLs was to create a URL from a URL string. Someone actually did end up asking for the API you are describing in the URL spec and discussion mostly stalled.

We have an API in Node.js for constructing URLs from parts - but that creates a string one would still need to pass to the URL constructor.

So this is likely not a bad idea and it is currently blocked on someone actually doing the work of adding that capability.


The only workaround I've found so far is to use minimal correct URL to initialize the object and then to override it's parts (namely protocol and host).

const url = new URL('https://example.com');

url.protocol = 'http';
url.host = 'google.com';

console.log(url.toString()); // outputs: http://google.com/

However, it's still cumbersome for this use case.

Tags:

Javascript

Url