JavaScript Interview Question #142

What are URL and URLSearchParams used for?

Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced

Quick Interview Answer

URL provides a structured API for parsing and constructing URLs. URLSearchParams provides methods for reading, adding, updating, and deleting query-string parameters.

Detailed Explanation

URL provides a structured API for parsing and constructing URLs. URLSearchParams provides methods for reading, adding, updating, and deleting query-string parameters.

These APIs are preferable to manually concatenating complex query strings because they correctly handle encoding and make URL manipulation easier to understand.

Code Example

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

url.searchParams.set("q", "JavaScript interview");
url.searchParams.set("page", "2");

console.log(url.toString());