I use this because there is special handling by the URLSearchParams objects (e.g. the question mark in the URL). Also, it allows other operations on the Params and URL if necessary.
You could loop over the param object's entries manually, instead creating a URLSearchParams object and using forEach.
Using it seems more foolproof, so it's probably a good idea unless you need high performance.
Code:
The check on params is needed in because it is an optional parameter. I use a fuller form of this function for an internal API library, so a query string is not always required.
In JS, this check should be done anyway, in theory. In TS, simply make it a mandatory parameter.
Note: URL.searchParams is a read only instance of URLSearchParams.
RE: Query strings
You can use
URLSearchParams
.I have this for one of my current projects:
I use this because there is special handling by the
URLSearchParams
objects (e.g. the question mark in the URL). Also, it allows other operations on the Params and URL if necessary.You could loop over the param object's entries manually, instead creating a
URLSearchParams
object and usingforEach
.Using it seems more foolproof, so it's probably a good idea unless you need high performance.
Code:
The check on
params
is needed in because it is an optional parameter. I use a fuller form of this function for an internal API library, so a query string is not always required.In JS, this check should be done anyway, in theory. In TS, simply make it a mandatory parameter.
Note:
URL.searchParams
is a read only instance ofURLSearchParams
.MDN Docs:
URL
URLSearchParams
Thanks, I didn't know about this.