Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

URLSearchParams iteration

Why does the second parameter remain after the loop has completed?

const queryParams = new URLSearchParams({
  first: 'something',
  second: 'something',
  third: 'something',
})

console.log('before', queryParams.toString())

for (const [key, value] of queryParams.entries()){
    queryParams.delete(key)
}

console.log('after', queryParams.toString())
.as-console-wrapper {
    max-height: 100% !important;
}

I expected it to be empty

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue with your code is that you are modifying the queryParams object while iterating over it using the for…of loop. When you delete an entry from the URLSearchParams object, it affects the iteration process, and unexpected behavior may occur.

To safely clear all parameters from the URLSearchParams object, you can use the URLSearchParams constructor without any parameters or use the URLSearchParams.clear() method. Here’s an updated version of your code:

const queryParams = new URLSearchParams({
  first: 'something',
  second: 'something',
  third: 'something',
});

console.log('before', queryParams.toString());

// Clearing parameters using the URLSearchParams constructor
const newQueryParams = new URLSearchParams();

console.log('after', newQueryParams.toString());

Or using the clear() method:

const queryParams = new URLSearchParams({
  first: 'something',
  second: 'something',
  third: 'something',
});

console.log('before', queryParams.toString());

// Clearing parameters using the clear() method
queryParams.clear();

console.log('after', queryParams.toString());

Either of these approaches will safely clear all parameters from the URLSearchParams object without affecting the iteration process.

If you want to delete entries from the URLSearchParams object while iterating, you need to create a copy of the entries first, and then iterate over the copy. This way, you won’t modify the object being iterated over. Here’s an example:

// Create a copy of entries
const entriesCopy = [...queryParams.entries()];

// Iterate over the copy and delete entries from the original object
for (const [key, value] of entriesCopy) {
  queryParams.delete(key);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading