Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Varun Barad
Varun Barad

Posted on • Originally published atvarunbarad.com on

     

JavaScript 30 - Array Cardio 1

Day 4 ofJS30 challenge, today I worked with various methods on array (I knew most of them beforehand) but I learned two cool things today.

The key concepts I learned from today’s challenge were:

  • Converting iterables to array in JS.
  • Displaying array of objects nicely formatted in console.

Converting iterables to array in JS

As you might have observed thatdocument.querySelectorAll doesn’t return us an actualArray but instead it returns us what is called as aNodeList. ConsequentlyNodeList doesn’t have all the methods that anArray does (likemap,filter,reduce etc).

NodeList is an example of what we call as “iterable” in JS. So whenever working with iterables we tend to prefer to convert them to an actualArray so that we have more options to work with.

I already knew of one way to convert them:

constanyIterable=document.querySelectorAll('a');constconvertedArray=Array.from(anyIterable);

Here we used theArray.from method to convert the iterable to anArray.

The other way I learned today was:

constanyIterable=document.querySelectorAll('a');constconvertedArray=[...anyIterable];

Here we made use of a combination of 2 things:

1. ES6 spread operator...

When we prepend an iterable with... (called the ES6 spread operator) what it does is it extracts all values from that iterable and replaces the...anyIterable part of the expression with those values.

2. Array literal[]

Then when we enclose the “spreaded” values with[ and] it converts the whole thing into an array containing all the values from that iterable.

Both produce the same result. I don’t know if one performs better than the other under large data-sets. But even though the[...anyIterable] way is more concise, to me theArray.from(anyIterable) usage seems more readable.

Conclusion

That’s all folks, that was it for today. If you have anything unclear in this article or want to discuss anything else, hit me up on twitter@varun_barad.

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

Lifelong learner & maker
  • Location
    India
  • Work
    Product Engineer at Obvious In
  • Joined

More fromVarun Barad

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