• JavaScript Video Tutorials

JavaScript - Set.values() Method



The Set.values() method in JavaScript returns an iterator object that contains all the values present in the set in the order of insertion. This iterator can be used to iterate over the values of the Set using a loop or methods like next(). This method allows you to access the elements stored in the set without relying on the keys or indices.

This method works similar to the keys() method

Syntax

Following is the syntax of JavaScript Set.values() Method −

values()

Parameters

This method does not accept any parameters.

Return value

This method returns an iterator object containing all the values present in the Set in insertion order.

Examples

Example 1

In the following example, we are iterating through the values 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('a');
      set.add('b');
      set.add('c');
      
      const iterator = set.values();
      for (const value of iterator) {
         document.write(value, "<br>");
      }
   </script>
</body>
</html>

If we execute the above program, it prints each value present in the set.

Example 2

In this example, we're using the values() method to create an iterator for the values in the Set. Then, we manually retrieve each value element using the next() method on the iterator.

<html>
<body>
   <script>
      const mySet = new Set(["apple", "banana", "orange"]);
      const iterator = mySet.values();
      document.write(iterator.next().value);
      document.write(iterator.next().value);
      document.write(iterator.next().value);
   </script>
</body>
</html>

As we can see in the output, it returned each value element 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.

Advertisements