HomeSoftware DevelopmentHow are parts ordered in a Set in JavaScript ?

How are parts ordered in a Set in JavaScript ?


Enhance Article

Save Article

Like Article

Enhance Article

Save Article

In JavaScript, a brand new object referred to as Set was launched within the ES6 model. The Set object is just like Map however the main distinction is that parts within the set are distinctive and repeated addition of the identical sort of parts just isn’t attainable. The set can retailer any sort of worth whether or not primitive or objects. The weather of a set are iterable. Parts are all the time iterated within the insertion order.

The weather of a set are ordered which implies that they are often accessed/iterated within the order of their insertion.

Syntax:

new Set([it]);

Instance 1: On this instance, we’ll create a fundamental set object and iterate over its parts to see the order.

Javascript

var pattern = new Set();

pattern.add("Hey");

pattern.add("Geek");

pattern.add("How");

pattern.add("Are");

pattern.add("You")

var knowledge = pattern.values();

for(var val of information) {

    console.log(val);

}

Output:

Hey
Geek
How
Are
You

Instance 2: On this instance, we’ll use an iterator to entry the weather of Set and confirm the order of parts.

Javascript

var pattern = new Set();

pattern.add("Hey");

pattern.add("Geek");

pattern.add("How");

pattern.add("Are");

pattern.add("You")

  

var getit = pattern[Symbol.iterator]();

console.log(getit.subsequent());

console.log(getit.subsequent());

console.log(getit.subsequent());

console.log(getit.subsequent());

console.log(getit.subsequent());

Output:

{worth: 'Hey', completed: false}
{worth: 'Geek', completed: false}
{worth: 'How', completed: false}
{worth: 'Are', completed: false}
{worth: 'You', completed: false}

Clarification: We are able to simply confirm that the weather within the set observe the identical order through which they’re inserted.

RELATED ARTICLES

Most Popular

Recent Comments