ES6 Set allows duplicate array/object

ecmascript-6, javascript

Solution

Why it is returning false at `items.has([5,6,7,8])`?

From MDN

The Set object lets you store unique values of any type, whether primitive values or object references.

The objects are compared using the reference, not the value. Sets uses `SameValueZero(x, y)` comparison algorithm to compare values. It says Return `true` if x and y are the same Object value. Otherwise, return `false`.

Why it is allowing duplicate values? I thought "A set is in an ordered list of values that cannot contain duplicates"

Same as #1. An non-primitive value is said to be already exists in set if the same object(not just same looking) already added in the set.

How to access array added by `items.add([5,6,7,8])`?

You've to create a variable and add the variable to the set. Then this variable can be used to check if set has that array or not.

Problem

Please have a look at the below script. I am testing it with Chrome. ``` /*declare a new set*/ var items = new Set() /*add an array by declaring as array type*/ var arr = [1,2,3,4]; items.add(arr); /*print items*/ console.log(items); // Set {[1, 2, 3, 4]} /*add an array directly as argument*/ items.add([5,6,7,8]); /*print items*/ console.log(items); // Set {[1, 2, 3, 4], [5, 6, 7, 8]} /*print type of items stored in Set*/ for (let item of items) console.log(typeof item); //object, object /*check if item has array we declared as array type*/ console.log(items.has(arr)); // true /*Now, check if item has array we added through arguments*/ console.log(items.has([5,6,7,8])); //false /*Now, add same array again via argument*/ items.add([1,2,3,4]); /*Set has duplicate items*/ console.log(items); // Set {[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]} ``` - Why it is returning false at `items.has([5,6,7,8])`? - Why it is allowing duplicate values? I thought "A set is in an ordered list of values that cannot contain duplicates" - How to access array added by `items.add([5,6,7,8])`?

Original source