Set.prototype.clear
Removes all elements from a Set object
Syntax
set.clear()Return Value
undefined
Examples
const set = new Set([1, 2, 3, 4, 5]);
console.log(set.size); // 5
set.clear();
console.log(set.size); // 0const selection = new Set<string>();
selection.add('item1');
selection.add('item2');
function clearSelection() {
selection.clear();
console.log('Selection cleared');
}const set = new Set(['x']);
set.clear();
console.log(set.has('x')); // falseUnderstanding Set.prototype.clear
The Set.prototype.clear method in JavaScript removes all elements from a Set object. It belongs to the Set object and is one of the most widely used methods for working with set values in modern JavaScript and TypeScript applications.
The method signature is set.clear(). When called, it returns undefined. Understanding when and how to use clear() helps you write more expressive, readable code.
Common use cases for Set.prototype.clear include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like set-delete, set-add, map-clear, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Set.prototype.clear is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
More Set Methods
Other methods in the Set object
Related Tools
More Set Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.