Welcome to my blog where I write mostly about technical things!

Destructuring Tweets – Episode 1 – Set() Trickery

This is a series where I (quickly) destructure one of those often shared snippet quizzes on Social Media. Welcome to the first episode!

Snippet

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

In the first line, they create a two-dimensional array. We have one (first dimension), holding numerous others (second dimension). All three of them contain a single item, a string. The 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 that only stores unique values. So whenever you pass an array, it automatically ditches all duplicated items. This API comes in handy at times. In this example, we construct a new set from the array myList.

The Output

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.

The Analysis

Why so? Cause an array is an object.

typeof [] // "object"

ℹ️ 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, the 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 truly the same.

Further Reading

https://medium.com/@naveenkarippai/learning-how-references-work-in-javascript-a066a4e15600
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
https://developer.mozilla.org/en-US/docs/Glossary/array