Austin Kregel
Austin Kregel

Reputation: 755

Simple Javascript Slideshow Explination

I have found this script on Codepen that has really peaked my interest, but it has me scratching my head as well. The entire code base isn't that large, in fact the whole slideshow script is only about 18 lines long. It's below,

(function(){
  var counter = 0, $items = document.querySelectorAll('.diy-slideshow section'),numItems = $items.length; 
  var showCurrent = function(){
    var itemToShow = Math.abs(counter%numItems);
    [].forEach.call( $items, function(el){
      el.classList.remove('show');
    });
    $items[itemToShow].classList.add('show');    
  };
  setInterval(function() {
     counter++;
     showCurrent();
  }, 5000);
})();  

So the part I am confused about is the showCurrent function. More spesifically, it is the part that is

[].forEach.call($items, function(el){...};

Now I understand that [] would be an array but I don't understand where it gets the values for the array, how does the function know that there are X number of items in the array to loop through? What makes [].forEach loop through all of the known elements?

Upvotes: 0

Views: 53

Answers (1)

Thomas Ruiz
Thomas Ruiz

Reputation: 3661

[].foreach.call is a shorthand for Array.prototype.foreach.call. Every javascript function is an object that has its own methods. call() is one of them.

The first argument of call() is thisArg, which represent the object that will behave as this during the function. In your example, $items (which is a DOMElement array) will be this in the foreach call.

Upvotes: 2

Related Questions