Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Lucian Rotari
Lucian Rotari
12,007 Points

JavaScript arrays and foreach loop

Hey everyone, I was searching on GitHub for a modal window script(I know I could use bootstrap one but I wanted some thing else)

I found a very good repository, it is very old but I find it very interesting. So I know that reading the source code of the library,plugin... is a good practice and that is what I did.

But Iā€™m stuck and want to understand this piece of code. I would appreciate if someone would explain it to me.

[].slice.call( document.querySelectorAll( '.md-trigger' ) ).forEach( function( el, i ) {

  // Code
}

Is this

var arrayOfElements = [];

arrayOfElements.slice.call( document.querySelectorAll( '.md-trigger' ) ).forEach( function( el, i ) {
  // code
}


 // the same as this

[].slice.call( document.querySelectorAll( '.md-trigger' ) ).forEach( function( el, i ) {

  // Code
}

And we loop through this empty array or something else?

1 Answer

Steven Parker
Steven Parker
229,732 Points

Yes, your two examples are equivalent, and what they do is loop through the element collection returned by "querySelectorAll".

The "querySelectorAll" function returns an HTMLCollection, which is much like an array but does not have a "slice" method (or a "forEach" method). The empty array is being used only to access the "slice" method, and the "call" is being used to change what it acts on from the empty array to the HTMLCollection. So in effect, this temporarily gives the HTMLCollection a "slice" method. The "slice" returns an array copy of the HTMLCollection and then "forEach" is applied to that.

But unless the loop does something unusual, the "slice" is most likely unnecessary. So this could be written a bit more compactly this way to apply the "forEach" directly:

[].forEach.call(document.querySelectorAll(".md-trigger"), function(el, i) { /* code */ });