The values() method of the Set object in JavaScript returns a new iterator object that yields the values for each element in the Set object in insertion order.
The syntax of Set.values() method is:
values()
This values() method of Set returns a new iterator object that yields the values for each element in the Set object in insertion order.
Set.values() returns value of type Iterator
.
In JavaScript, we can use the values()
method to get an iterator object and use it to iterate over the elements of a Set.
For example,
letters
with initial values 'a', 'b', and 'c'.values()
method to get an iterator object iterator
for the letters
Set.for...of
loop to iterate over the iterator
and log each value to the console using console.log()
.const letters = new Set(['a', 'b', 'c']);
const iterator = letters.values();
for (const value of iterator) {
console.log(value);
}
a b c
In JavaScript, we can use the values()
method to convert a Set object to an array.
For example,
numbers
with initial values 1, 2, and 3.values()
method to get an iterator object iterator
for the numbers
Set.iterator
to an array using the Array.from()
method and store it in the variable arrayOfValues
.arrayOfValues
to the console using console.log()
.const numbers = new Set([1, 2, 3]);
const iterator = numbers.values();
const arrayOfValues = Array.from(iterator);
console.log(arrayOfValues);
[ 1, 2, 3 ]
In JavaScript, we can use the values()
method to iterate over a Set object containing objects.
For example,
people
with initial objects representing different people.values()
method to get an iterator object iterator
for the people
Set.for...of
loop to iterate over the iterator
and log each value to the console using console.log()
.const person1 = { name: 'John' };
const person2 = { name: 'Jane' };
const people = new Set([person1, person2]);
const iterator = people.values();
for (const value of iterator) {
console.log(value);
}
{ name: 'John' } { name: 'Jane' }
In this JavaScript tutorial, we learned about values() method of Set: the syntax and few working examples with output and detailed explanation for each example.