So recently I’ve discovered a weird construct in Vanilla JS that I haven’t seen before: the URL method. It looks like something like this:

1
2
3
4
5
const url = new URL(`${covalentAPI}${APIEndpoint}/`);
url.search = new URLSearchParams({
    key: APIKEY,
    tickers: tickers
})

So after googling a little bit, I figured out what it does.

URL method

The URL method creates a new URL object. You can think of an URL object as a more convenient way of extracting and using different parts of URLs. The URL object has the following attributes:

AttributeExample
hrefhttps://api.covalenthq.com/v1/pricing/tickers/
originhttps://api.covalenthq.com
passwordnot in example, but returns a string containing the password specified in the domain name
pathname/v1/pricing/tickers/
portreturns the port number
protocolhttps:
search?key=ckey_docs&tickers=BTC%2CWETH%2CDAI%2CAAVE begins with the leading ? character
searchParamsobject used to access individual query params
usernamestring containing username specified in domain name

Creating new URL object

To create a new URL object, you use new URL(), supplying either an absolute URL, or a relative URL string and a base URL string.

Absolute:

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

Relative:

const url = new URL('../cats', 'http://www.example.com/dogs'
console.log(url) –> url = http://www.example.com/cats

URLSearchParams

Within the code, there is a URLSearchParams() method that is quite mysterious.

1
2
3
4
url.search = new URLSearchParams({
    key: APIKEY,
    tickers: tickers
})

In this case, we’re creating a new URLSearchParams object, and assigning its value to url.search.

Before this assignment, url.search returns empty. After the assignment, url.href returns:

1
https://api.covalenthq.com/v1/pricing/tickers/?key=ckey_docs&tickers=BTC%2CWETH%2CDAI%2CAAVE

while url.search returns:

1
?key=ckey_docs&tickers=BTC%2CWETH%2CDAI%2CAAVE

That’s it! The URL object is just an easier way for us to manipulate and extract GET request information, a handy little tool for API based calls.