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!
const myList = [['❤️'], ['JSSnippets'], ['❤️']]; const mySet = new Set(myList); console.log(mySet.size);
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
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,
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.
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.
- Trickery: one thinks one array gets ditched since it holds the same value
- Key Learning: objects are assigned by reference, not by value
- Further reading:
See you next Sunday! 🖖