JavaScript Set entries() Method Tutorial

In this section, we will learn what the Set entries() method is and how to use it in JavaScript.

What is JavaScript Set entries() Method?

Each value that we put in a `Set` object is considered as one entry. So via the `entries()` method, we can get an iterator object that contains the entire entries of the target `Set` object.

Note: In the Iterator section we’ve explained in greater details how to work with iterators, but in short, one way to get the contents of such an object is to use the `for of` loop. Basically, the `for of` will loop through all the content of the target iterator object and return all the entries one at a time.

JavaScript Set entries() Method Syntax:

entries();

entries() Function Parameters:

The method does not take an argument.

entries() Function Return Value:

The return value of this method is an iterator object that contains all the entries of the target Set object.

Example: using Set entries() method in JavaScript

const collect = new Set();
collect.add("Jack");
collect.add("Jack");
collect.add("Omid");
collect.add("John");
collect.add(100);
collect.add(200);

for (const entry of collect.entries()){
    console.log("***");
    console.log(`The entry is: ${entry}`);
    console.log(`The key of this entry is: ${entry[0]} and the value is: ${entry[1]}`);
  }

Output:

***

The entry is: Jack,Jack

The key of this entry is: Jack and the value is: Jack

***

The entry is: Omid,Omid

The key of this entry is: Omid and the value is: Omid

***

The entry is: John,John

The key of this entry is: John and the value is: John

***

The entry is: 100,100

The key of this entry is: 100 and the value is: 100

***

The entry is: 200,200

The key of this entry is: 200 and the value is: 200

Notes:

  • Each of the entries that we get back from the `entries()` method is essentially an array of only two elements. The first and the second elements of this array are the same.
  • Note: the `entries()` method is used in `Map` and `Array` objects as well. In those objects, the first and the second argument are `keys` and `values` respectively. So making this method behave similarly in the `Set` object as well, the committee used the same structure except the first and the second arguments are values. This is basically for creating a consistent API.
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies