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:
constmyList=[['❤️'],['JSSnippets'],['❤️']];constmySet=newSet(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 arraymyList
.
What will theconsole.log
be then? One might think the output will be2
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"
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 isassigned-by-reference. Primitive types (String, undefined, Number, etc.) areassigned-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
- 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! 🖖
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse