DEV Community

Kai
Kai

Posted on • Updated on

Destructuring Tweets - Episode 1 - Set() Trickery

Hey, I thought about creating this series, where I (quickly) destructor one of those often shared snippet quizzes on Twitter. Welcome to the first episode!

Snippet from @SnippetsJs:

const myList = [['❤️'], ['JSSnippets'], ['❤️']];
const mySet = new Set(myList);
console.log(mySet.size);
Enter fullscreen mode Exit fullscreen mode

In the first line, they create a two-dimensional array. Meaning we have one (first dimension), holding numerous others (second dimension). All three of them contain a single item being a string. Remarkable here is that the first and last item is the same!
In the second line, they create a Set. You might not have heard of it, but it's an object to only store unique values. So whenever you pass an array, it automatically ditches all duplicated items. This API comes in handy at times. What we do in this example is constructing a new set from the array myList.
What will the console.log be then? One might think the output will be 2 since the first and last array is equal. Well, surprisingly enough, this is wrong! The result is, indeed, 3.
Why so? Cause an array is an object.

typeof [] // "object"
Enter fullscreen mode Exit fullscreen mode

On a side-note: even the indexes are just properties. We access an index by its property-name like any other (e.g. myArray[5]).
However, important here is that an object is assigned-by-reference. Primitive types (String, undefined, Number, etc.) are assigned-by-value. So even though an object might hold the same properties and values, it's still not similar since it's another reference. Think about it in the sense that every object has its unique ID. Only if said IDs match they are the same.

Snippet summary

See you next Sunday! 🖖

Top comments (0)