1

So, I'm following a tutorial where we are making a youtube search engine that will display some videos from youtube. This was the first video where the instructor mentioned the each loop. I looked on JQuery documentation but still cant wrap my head around what exactly this each loop is trying to do. I was following well with the instructor until he brought in the each loop near the end of the code below. I'm not too sure what the instructor is doing with this loop. Any insight would be helpful

function search()
{
    $('#results').html('');
    $('#buttons').html('');

    // get form input
    q = $('#query').val();

    //run GET Request on API

    $.get(
    "https://www.googleapis.com/youtube/v3/search",{
        part:'snippet,id',
        q:q,
        type: 'video',
        key:'AIzaSyCadgai_XAKk2TYQH1f5lXrR5QEHWXowfA'
        },
        function(data)
    {
        var nextPageToken = data.nextPageToken;
        var prevPageToken = data.prevPageToken;
        // Log data
        console.log(data);

        $.each(data.items,function(i,item))
        {
               var output = getOutput(item);

        $('#results').append(output);
               }

    }
    );

}
8
  • It simply iterate over data.items (The first parameter) and the callback function (The second parameter) is appending each value in the collection into #results (A DOM element with id results) - The i is the current index being iterated and item is the actual item in that index Commented May 31, 2016 at 16:48
  • $.get is returning data, which is conveniently named data in this code. Within data there is an array name items. Therefore, $.each(data.items) is iterating through each of the items in the items array. As it iterates through the items, function(i,item) is the way of assigning the current item to the item variable. It then passes each item to getOutput() and appends its return value to #results. Commented May 31, 2016 at 16:49
  • oh.. this whole time I was under the impression it was function data(), not function(data). I guess thats what happens when I just mindlessly copy the instructor. What exactly does putting data in function() do? I thought we must name all functions. like function search(){ stuff here}, atleast thats what we have been doing in the course until now. Commented May 31, 2016 at 16:55
  • @Munt you could name this function (For example function myFunc(i,item) { ..... }) and then pass it to the $.each loop by doing $.each(data.items,myFunc) (Note that i only pass the name of the function without " () " after it, the $.each loop will invoke it for you, and you can also reuse this function manually, or with more $.each loops the same way) Commented May 31, 2016 at 16:59
  • @Munt: This is an anonymous function. In JavaScript, functions are objects like any other object. In this callback syntax you're simply defining an unnamed function (function (data) { ... }) which will be invoked. Inside of the implementation for each() the function is named as the parameter to each(). You can see a simple example of this concept here: jsfiddle.net/rc23wLac Where a function is defined which itself expects a function to be passed to it. Then I call that function and pass an anonymous function to it. Commented May 31, 2016 at 17:00

2 Answers 2

1

It's basically just a loop, but using the jQuery function syntax. The benefit of that syntax is when you want to loop over a selected set of DOM elements, since the core of jQuery's usefulness is the simplicity with which is queries the DOM. While it also works for any collection, it's not always necessary (unless you just want to use the syntax for consistency).

.each() simply iterates over the elements it's given, invoking the supplied function on each one. Within the function, i is the index (0 through the element count minus 1) and item is the current element. (And those two parameters can be named whatever you like, to keep your code clear and understandable.)

Basically, this:

$.each(data.items,function(i,item))
    {
        var output = getOutput(item);
        $('#results').append(output);
    });

is reasonably similar to this:

for (var i = 0; i < data.items.length; i++) {
    var output = getOutput(data.items[i]);
    $('#results').append(output);
}
Sign up to request clarification or add additional context in comments.

13 Comments

hmm, how does the each loop know to do i++? this is default? So we have to specify if we wanted to change i by 3 each time for example? Also is data.items from the youtube API? I havent defined data.items anywhere in my code and suddenly we are just looping from the items.
@Munt: The implementation of the .each() function in jQuery increments i. And yes, if you want to increment by anything other than 1 you will likely need to just write your own loop instead of using the .each() function. data (in this case) is simply the object that comes back from the YouTube API (the AJAX call being made by the .get() function), and items is a property on that object (an array, specifically).
@Munt I don't believe you can modify the iterator of .each(). It will simply iterate, one at a time, over every element in whatever data set you are telling it to iterate over. Also, yes, data.items is coming from your ajax request. That is the data that the youtube API is sending you in response to your request.
@Munt: You're not setting data. The get() function is collecting information from the AJAX request (which you can see on the network tab in your browser debugging tools) and is passing that information as an object to the callback function you supply to get(). Notice the parameter for that function is called data. You can call that parameter anything you like, and just update the code within the function accordingly.
@Munt: Yes, you can name your function parameter anything you like. Nothing outside of a function needs to know what a parameter is named, whatever it passed to the function will be in that parameter. I'm not really sure how else to explain it, this is part of pretty much every programming language I've seen. When you define a function, you can define parameters that the function expects to be given. When you call that function, you pass values to those parameters.
|
0

By looking at the code, I can tell that the response that you are getting back from the ajax call is an object. Said object has a property called items. Since the instructor is "foreaching" the items property, I can conclude that it is an array. Therefore, the .each() is iterating over every item in the data.items array to perform an action on each of them.

Now, you have not included the code for the getOutput() function, but based on the rest of the code, I can see that it is generating HTML markup using the current item in the .each() loop. After getting the HTML markup from getOutput(), it is appending the HTML to an element with the id="results" which will display it on the screen (assuming the results element is visible).

Hope that helps you understand what it's doing!

1 Comment

Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.