Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Kai
Kai

Posted on • Edited 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:

constmyList=[['❤️'],['JSSnippets'],['❤️']];constmySet=newSet(myList);console.log(mySet.size);
Enter fullscreen modeExit 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 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"
Enter fullscreen modeExit 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 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

See you next Sunday! 🖖

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Moved my blog to blog.ungra.dev.
  • Location
    Stuttgart
  • Work
    Senior Software Engineer at Team One Developers
  • Joined

More fromKai

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp