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
2
Answers
Here’s what happens when your code is executed:
second=something, and third=something.
and third=something.
now third=something because the original second pair
(second=something) has shifted up in the order after the deletion of
the first pair.
Try this one:
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:
Or using the clear() method:
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: