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

Need help to understand this Javascript snippet of code :)

Hello, can anyone explain this code, what it does, (each line of code) im new to javascript,

var nodes = document.getElementsByTagName('video');
var videos = Array.prototype.slice.call(nodes);
videos.forEach(function(video) {
  video.volume = 0.5;
});

1 Answer

Hey erdrag,

This first line selects each element on the page and puts it into a NodeList/HTMLCollection (depending on the browser). This is an array-like object that gets each element by the tag name and stores them into this object.

var nodes = document.getElementsByTagName('video');

The second line takes the NodeList/HTMLCollection received from the variable nodes and converts it into an array object. The call is made to nodes which is used with the slice function to return a copy of an array. Since the original object was not an array, we have to use "Array.prototype" in order to convert it into an array.

var videos = Array.prototype.slice.call(nodes);

This final line iterates over each object in the array. The variable in the function call video is used as a substitute for each individual element stored in the array. And then you are setting each video element to a volume of 0.5 or 50%.

videos.forEach(function(video) {
  video.volume = 0.5;
});

Does that make more sense?

Hello, as i said im new to javascript, and i have not learned so much about arrays and other calls

can you explain what an "Array" is and what "slice" and "call" does

Kind regards

// erdrag

I would recommend checking out the MDN (Mozilla Developer Network) which is an excellent resource to look up what each and every function is in a number of APIs, including the Web API. Their articles can explain each function far better than I can.

Just head on over to: https://developer.mozilla.org and search for what you're looking for.

Okey thanks for providing the link,

and thanks for explaining the code in your first comment! i appreciate it alot:)

// erdrag