Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
221,292 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 */ });