Certainly, here are examples illustrating the use of Set
and WeakSet
in ES6:
https://onecompiler.com/javascript/423ctrkr3
Set Example:
// Creating a Set
const mySet = new Set();
// Adding elements to the Set
mySet.add(1);
mySet.add('Hello');
mySet.add({ key: 'value' });
// Checking for existence
console.log(mySet.has(1)); // true isme kewal unique value hi show krta hai matalab Set me kewal 2 value same hogi to ek baar hi show krega
// Iterating through the Set
mySet.forEach((item) => {
console.log(item);
});
// Deleting an element
mySet.delete('Hello');
// Size of the Set
console.log(mySet.size); // 2
In this example, a Set
is created and populated with various data types. It demonstrates adding, checking for existence, iterating, deleting, and obtaining the size of the set.
WeakSet Example:
// Creating objects
let obj1 = { name: 'Object 1' };
let obj2 = { name: 'Object 2' };
// Creating a WeakSet
const myWeakSet = new WeakSet();
// Adding objects to the WeakSet
myWeakSet.add(obj1);
myWeakSet.add(obj2);
// Checking for existence
console.log(myWeakSet.has(obj1)); // true
// Removing an object (Not possible directly; relies on external references)
// Letting an object go out of scope
obj1 = null;
// Checking for existence after object is out of scope
console.log(myWeakSet.has(obj1)); // false
In this WeakSet
example, two objects are added to the WeakSet. Importantly, when an object goes out of scope and is no longer referenced externally, it becomes eligible for garbage collection, and the corresponding entry in the WeakSet is automatically removed. The WeakSet is useful in scenarios where the lifecycle of elements should be tied to external references.
The choice between Set
and Array
in JavaScript depends on the specific requirements of your data and the operations you need to perform. Here's a comparison between Set
and Array
:
Set:
-
Uniqueness:
-
Set:
- Enforces uniqueness of elements. It cannot contain duplicate values.
-
Array:
- Allows duplicate values. Each element is distinct, and repetition is possible.
-
Set:
-
Order:
-
Set:
- Maintains the order of insertion of elements.
-
Array:
- Preserves the order of elements based on their indices.
-
Set:
-
Use Case:
-
Set:
- Ideal when ensuring unique values or checking membership efficiently.
-
Array:
- Suitable for ordered collections where duplicates are allowed and random access to elements is necessary.
-
Set:
-
Methods:
-
Set:
- Provides methods like
add
,delete
,has
, andforEach
for manipulating elements.
- Provides methods like
-
Array:
- Offers a wide range of methods for manipulation, such as
push
,pop
,splice
, andmap
, catering to various array operations.
- Offers a wide range of methods for manipulation, such as
-
Set:
Example - Set:
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
console.log(mySet.has(2)); // true
console.log(mySet.size); // 3
Example - Array:
const myArray = [1, 2, 3, 2];
console.log(myArray.includes(2)); // true
console.log(myArray.length); // 4
In the Set example, duplicate values are automatically ignored. In the Array example, duplicate values are retained.
When to Choose:
- Use
Set
when you need a collection of unique values and the order of insertion matters. - Use
Array
when you require an ordered collection, and duplicates are acceptable, or when you need to perform various array-specific operations.
In summary, while Set
is specialized for unique values with efficient membership checks, Array
is more versatile and appropriate for scenarios where ordering and duplicates are part of the requirements.
Let's analyze the provided JavaScript code step by step:
- Creating a Set and Adding Elements:
const mySet = new Set();
mySet.add(1);
mySet.add('Hello');
mySet.add({ key: 'value' });
mySet.add([{ key1: 'value1', key2: 'value1-2' }]);
mySet.add(1);
mySet.add('Hello');
This code initializes a Set
named mySet
and adds various elements, including numbers, strings, and objects. Note that duplicates are automatically ignored in a Set
.
- Converting Array to Set:
let newArray=[1,2,3,44,5,2,1];
newArray=new Set(newArray);
console.log("Line18-", [...newArray]);
The array newArray
is converted to a Set
, and the spread operator ([...newArray]
) is used to convert it back to an array. This demonstrates how a Set
automatically handles duplicate values.
- Checking for Existence and Iterating through the Set:
console.log("Line23-", mySet.has(1)); // true
mySet.forEach((item) => {
console.log(item);
});
The code checks for the existence of the value 1
in the Set
using has()
. It then iterates through the Set
using forEach()
.
- Deleting an Element and Getting the Size:
mySet.delete('Hello');
console.log("Line34-", mySet.size); // 2
The code deletes the value 'Hello' from the Set
and retrieves its size.
- Exceptional Case with Objects:
const mySett = new Set();
mySett.add([{ key1: 'value1', key2: 'value1-2' }]);
mySett.add([{ key1: 'value1', key2: 'value1-2' }]);
console.log("Line40-", mySett);
This part illustrates that even though the array elements contain the same values, they are treated as distinct objects within the Set
. Each object reference is unique.
- Converting Array with Nested Arrays to Set:
let newArray1=[1,[2,4,4,5,2],3,44,5,2,1,44,[2,3,45,44],[2,3,45,44]]
newArray1=new Set(newArray1)
console.log("Line44-",newArray1)
Similar to the previous example, this part demonstrates that a Set
treats nested arrays as distinct elements. Duplicates are not ignored based on the values within the nested arrays.
The provided code showcases various aspects of working with a Set
in JavaScript, emphasizing uniqueness and automatic handling of duplicates. Additionally, it illustrates the behavior with objects and nested arrays within a Set
.
Top comments (0)