JavaScript Set keys()
Syntax & Examples
Set.keys() method
The keys() method of the Set object in JavaScript is an alias for the values() method. It returns a new iterator object that contains the values for each element in the Set object in insertion order.
Syntax of Set.keys()
The syntax of Set.keys() method is:
keys()This keys() method of Set an alias for Set.prototype.values().
Return Type
Set.keys() returns value of type Iterator.
✐ Examples
1 Using keys() to iterate over a Set
In JavaScript, we can use the keys() method to get an iterator object and use it to iterate over the elements of a Set.
For example,
- Create a new Set object
letterswith initial values 'a', 'b', and 'c'. - Use the
keys()method to get an iterator objectiteratorfor thelettersSet. - Use a
for...ofloop to iterate over theiteratorand log each value to the console usingconsole.log().
JavaScript Program
const letters = new Set(['a', 'b', 'c']);
const iterator = letters.keys();
for (const value of iterator) {
console.log(value);
}Output
a b c
2 Using keys() to convert a Set to an array
In JavaScript, we can use the keys() method to convert a Set object to an array.
For example,
- Create a new Set object
numberswith initial values 1, 2, and 3. - Use the
keys()method to get an iterator objectiteratorfor thenumbersSet. - Convert the
iteratorto an array using theArray.from()method and store it in the variablearrayOfKeys. - Log
arrayOfKeysto the console usingconsole.log().
JavaScript Program
const numbers = new Set([1, 2, 3]);
const iterator = numbers.keys();
const arrayOfKeys = Array.from(iterator);
console.log(arrayOfKeys);Output
[ 1, 2, 3 ]
3 Using keys() with a Set of objects
In JavaScript, we can use the keys() method to iterate over a Set object containing objects.
For example,
- Create a new Set object
peoplewith initial objects representing different people. - Use the
keys()method to get an iterator objectiteratorfor thepeopleSet. - Use a
for...ofloop to iterate over theiteratorand log each value to the console usingconsole.log().
JavaScript Program
const person1 = { name: 'John' };
const person2 = { name: 'Jane' };
const people = new Set([person1, person2]);
const iterator = people.keys();
for (const value of iterator) {
console.log(value);
}Output
{ name: 'John' }
{ name: 'Jane' }Summary
In this JavaScript tutorial, we learned about keys() method of Set: the syntax and few working examples with output and detailed explanation for each example.