Course contentsShow
← Web Development
Lesson 955 of 2,98217. URL and History ManagementFree lesson

Iterating Over Parameters

Using forEach(), entries(), keys(), and values() to loop through query parameters.

Iterating Over Parameters

What you'll learn: How to loop through all query parameters in a URL using URLSearchParams iteration methods.

Now that you know how to read, add, and remove individual query parameters, you'll often need to process all parameters in a URL—perhaps to display them, validate them, or transform them. URLSearchParams provides several methods to iterate through parameters just like you would with arrays or objects.

Available Iteration Methods

forEach()

The most straightforward way to loop through parameters. It calls a function for each key-value pair:

const params = new URLSearchParams('category=books&price=20&sale=true');

params.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});
// Output:
// category: books
// price: 20
// sale: true

entries()

Returns an iterator of [key, value] pairs, perfect for for...of loops:

for (const [key, value] of params.entries()) {
  console.log(`${key} = ${value}`);
}

keys()

Iterates through just the parameter names:

for (const key of params.keys()) {
  console.log(`Parameter: ${key}`);
}
// Output: Parameter: category, Parameter: price, Parameter: sale

values()

Iterates through just the parameter values:

for (const value of params.values()) {
  console.log(`Value: ${value}`);
}
// Output: Value: books, Value: 20, Value: true

Practical Use Cases

These methods shine when you need to convert parameters to an object, validate all inputs, or build analytics data from URLs.

Key Takeaway: URLSearchParams offers forEach(), entries(), keys(), and values() methods to iterate through query parameters, giving you flexible options depending on whether you need names, values, or both.