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)
For further actions, you may consider blocking this person and/orreporting abuse