Course contentsShow
← JavaScript
Lesson 2315 of 2,72347. Networking PrimitivesFree lesson

Iterating Over Query Parameters

Iterate through query parameters using forEach(), entries(), keys(), and values() methods on URLSearchParams objects.

Iterating Over Query Parameters

You'll learn how to loop through all query parameters in a URL using the built-in iteration methods of URLSearchParams.

The Core Idea

Once you've created a URLSearchParams object, you often need to process all its key-value pairs rather than accessing them one at a time. URLSearchParams implements the iterable protocol, giving you several ways to loop through parameters: forEach() for side-effects, entries() for key-value pairs, keys() for just parameter names, and values() for just the values.

Iteration Methods

forEach()

Executes a function for each parameter, similar to arrays:

const params = new URLSearchParams("color=blue&size=large&color=red");

params.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});
// Output:
// color: blue
// size: large
// color: red

entries()

Returns an iterator of [key, value] pairs:

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

keys()

Returns an iterator of just parameter names:

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

values()

Returns an iterator of just parameter values:

for (const value of params.values()) {
  console.log(`Value: ${value}`);
}
// Output: blue, large, red

Think of It Like...

Imagine a URLSearchParams object as a filing cabinet where each drawer has a label (key) and contents (value). These iteration methods let you walk through every drawer systematically—whether you need both label and contents (entries), just labels (keys), just contents (values), or want to perform an action on each (forEach).

Key Takeaway: URLSearchParams provides four iteration methods—forEach(), entries(), keys(), and values()—allowing flexible traversal of all query parameters, including duplicates.