Skip to content

How to get value from Set in JavaScript

  • by

In JavaScript, you cannot directly access elements in a Set using indexes as you would with an array. Sets are designed to store unique values without any specific order.

However, you can iterate over the elements of a Set using the forEach method or the for...of loop. Additionally, you can convert a Set to an array to access specific values using array indexing. Keep in mind that Sets do not guarantee a specific order for the elements.

Get value from Set in JavaScript example

Simple example code.

const mySet = new Set();
mySet.add('apple');
mySet.add('banana');
mySet.add('orange');

// Using forEach
mySet.forEach((value) => {
  console.log(value);
});

// Using for...of loop
for (const value of mySet) {
  console.log(value);
}

Output:

How to get value from Set in JavaScript

Both the forEach method and the for...of loop will iterate over the elements in the Set, allowing you to access the values.

If you need to perform specific operations on the elements of a Set or check if a particular value exists in the Set, you can use the has method:

if (mySet.has('banana')) {
  console.log('Set contains "banana"');
}

The has method returns true if the value exists in the Set, and false otherwise.

How to get individual key values from the “Set” Object in JavaScript?

Answer:


In JavaScript, the Set object does not have keys or key-value pairs like an object or a Map. Sets are designed to store unique values, and the values themselves act as both the key and the value.

If you want to access individual values from a Set, you can iterate over the Set using the forEach method or the for...of loop, as mentioned in the above example.

Comment if you have any doubts or suggestions on this Js set topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *