Write toQueryString(params) that turns an object into a URL query string.
Before you start
What's a query string, and what's percent-encoding?
A query string is the part of a URL after the ?. It carries extra information for the page or the server, such as a search term, a filter, or a page number, as key=value pairs joined by &. It runs to the end of the URL, or to a #, which starts the fragment, the part that points to a place within the page. Everything in it is text: page=2 carries the string "2". Here's a shop's search URL, https://shop.example/search?q=fish+%26+chips&tag=sale&tag=new&page=2, taken apart:
| Pair | Key | Value |
|---|---|---|
q=fish+%26+chips | q | fish & chips. Each + stands for a space, and %26 is an & that belongs to the value. |
tag=sale | tag | sale |
tag=new | tag | new. A key can appear more than once; that's a common way to send a list. |
page=2 | page | 2, as text |
The value fish & chips couldn't go in as it is: its & would be read as the start of a new pair, and a URL can't contain spaces. A # in a value would end the query too. Percent-encoding writes such a character as % followed by two hexadecimal digits, the value of its byte: a space is byte 32, or 20 in hex, so it becomes %20. A character outside ASCII (the basic English letters, digits, and symbols) is first turned into its bytes in UTF-8, the standard text encoding, so é, which takes two bytes, becomes %C3%A9. A % itself becomes %25. JavaScript's encodeURIComponent encodes one key or value this way, and decodeURIComponent reverses it:
encodeURIComponent("fish & chips"); // "fish%20%26%20chips"
encodeURIComponent("1+1=2"); // "1%2B1%3D2"
encodeURIComponent("café"); // "caf%C3%A9"
decodeURIComponent("caf%C3%A9"); // "café"
decodeURIComponent("fish+%26+chips"); // "fish+&+chips": it leaves + alone
Spaces have a second spelling. When an HTML form sends its fields in a query string, it writes each space as +, and most code that reads query strings, URLSearchParams included, reads every + as a space. So a real plus sign has to travel as %2B. encodeURIComponent writes spaces as %20, which every reader understands.
You meet query strings in search pages, filters, pagination, and tracking links, and you add them to fetch requests. Browsers and Node.js have URLSearchParams, also available as url.searchParams on a URL object, which reads and writes them for you.
Encode keys and values with encodeURIComponent and join the pairs with &. An array value adds the key once per item. Skip values (and array items) that are null or undefined, but keep 0, false, and "". Don't add a leading ?.
function toQueryString(params) {
// your code
}
// toQueryString({ q: "red shoes", page: 2, tags: ["a", "b"], sort: undefined });
// → "q=red%20shoes&page=2&tags=a&tags=b"
Solve it in the editor, with tests
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…