set.clear() removes every value from a Set, so its size becomes 0. It is the quickest way to empty a Set and start again.
The Set object itself is not replaced. It is the same object as before, only empty. So every variable that points to the Set sees the change. The method returns undefined.
Remember
set.clear()
before → set.size is 3 (for example)
after → set.size is 0
returns → undefined
Same Set object, now empty
Other variables that point to it see the change
Visit in order.forEach() gives the callback 1, then 2, and the code saves each number in seen.
Clear in the middle. When n is 2, queue.clear() removes all values, including 3 and 4 that were not visited yet.
The loop ends early. A Set only visits values that are still inside, so 3 and 4 are never reached and the final size is 0.
Compatibility
Browser & Runtime Support
Set.prototype.clear() is part of ES2015 (ES6), together with Set itself. Every current browser and Node.js has it.
✓ ES2015 · Widely supported
set.clear()
Supported in Chrome 38+, Edge 12+, Firefox 37+, Safari 9+, Opera 25+ and Node.js 4+. Internet Explorer 11 only has a basic Set.
ES2015Standard since
Google Chrome38+ · Desktop & Mobile
Full support
Microsoft Edge12+ · Chromium based
Full support
Mozilla Firefox37+ · Desktop & Mobile
Full support
Apple Safari9+ · macOS & iOS
Full support
Opera25+ · Chromium based
Full support
Samsung InternetRecent versions · Android
Supported
Android WebView38+ · Chromium based
Supported
Node.js4+ · Server runtime
Supported
DenoRecent versions · JavaScript runtime
Supported
BunRecent versions · JavaScript runtime
Supported
Internet ExplorerIE 11 · basic Set only
Partial support
set.clear()Excellent
Bottom line: Safe to use in every current browser and in Node.js. Only Internet Explorer needs special care.
Frequently Asked Questions
It removes every value from a Set, so the size becomes 0. The Set object itself stays the same and can be used again. The method returns undefined.
clear() empties the same Set object, so every variable that points to it sees an empty Set. set = new Set() only points one variable at a new empty Set, and other variables keep the old one with its values.
No. The values are removed for good. If you may need them again, make a copy first with const backup = new Set(set), and use the copy later.
No. It returns undefined. To check the result, read set.size, which is 0 after the call.
It is shorter and clearer, and it removes everything in a single call. For a normal-sized Set the speed difference does not matter, so choose clear() because it says exactly what you mean.