JavaScript Set values()
Syntax & Examples

Set.values() method

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.


Syntax of Set.values()

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.

Return Type

Set.values() returns value of type Iterator.



✐ Examples

1 Using values() to iterate over a Set

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,

  1. Create a new Set object letters with initial values 'a', 'b', and 'c'.
  2. Use the values() method to get an iterator object iterator for the letters Set.
  3. Use a for...of loop to iterate over the iterator and log each value to the console using console.log().

JavaScript Program

const letters = new Set(['a', 'b', 'c']);
const iterator = letters.values();
for (const value of iterator) {
  console.log(value);
}

Output

a
b
c

2 Using values() to convert a Set to an array

In JavaScript, we can use the values() method to convert a Set object to an array.

For example,

  1. Create a new Set object numbers with initial values 1, 2, and 3.
  2. Use the values() method to get an iterator object iterator for the numbers Set.
  3. Convert the iterator to an array using the Array.from() method and store it in the variable arrayOfValues.
  4. Log arrayOfValues to the console using console.log().

JavaScript Program

const numbers = new Set([1, 2, 3]);
const iterator = numbers.values();
const arrayOfValues = Array.from(iterator);
console.log(arrayOfValues);

Output

[ 1, 2, 3 ]

3 Using values() with a Set of objects

In JavaScript, we can use the values() method to iterate over a Set object containing objects.

For example,

  1. Create a new Set object people with initial objects representing different people.
  2. Use the values() method to get an iterator object iterator for the people Set.
  3. Use a for...of loop to iterate over the iterator and log each value to the console using console.log().

JavaScript Program

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);
}

Output

{ name: 'John' }
{ name: 'Jane' }

Summary

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.