JavaScript - Set.keys() Method
The Set.keys() method in JavaScript returns an iterator object containing the values of the elements in a Set object, in insertion order.
This method is an alias for the JavaScript values() method.
Syntax
Following is the syntax of JavaScript Set.keys() method −
keys()
Parameters
This method does not accept any parameters.
Return value
This method returns an iterator object containing the values of the elements in the set, in insertion order.
Examples
Example 1
In the following example, we are iterating through the element of the Set object using the keys() method and printing them with a for...of loop from the result of the keys() method.
<html>
<body>
<script>
const set = new Set();
set.add('apple');
set.add('banana');
set.add('cherry');
const iterator = set.keys();
for (const value of iterator) {
document.write(value, "<br>");
}
</script>
</body>
</html>
The above program returns a new set iterator object "iterator" that contains the values of this Set in insertion order.
Example 2
In this example, we're using the keys() method to create an iterator for the values in the Set. Then, we manually retrieve each value using the next() method on the iterator.
<html>
<body>
<script>
const set = new Set();
set.add('a');
set.add('b');
set.add('c');
const iterator = set.keys();
document.write(iterator.next().value, "<br>");
document.write(iterator.next().value, "<br>");
document.write(iterator.next().value);
</script>
</body>
</html>
As we can see in the output, it returned each value present in the set.
Example 3
In the following example, we are using the spread operator (...) to convert the iterator returned by the values() method into an array containing all the values of the set.
<html>
<body>
<script>
const mySet = new Set(["apple", "banana", "orange"]);
const valuesArray = [...mySet.values()];
document.write(valuesArray);
</script>
</body>
</html>
If we execute the above program, it returns an array containing each value from the set.