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);
}
}
);
}
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 idresults) - Theiis the current index being iterated anditemis the actual item in that index$.getis returning data, which is conveniently nameddatain this code. Withindatathere is an array nameitems. Therefore,$.each(data.items)is iterating through each of the items in theitemsarray. As it iterates through the items,function(i,item)is the way of assigning the current item to theitemvariable. It then passes each item togetOutput()and appends its return value to#results.function myFunc(i,item) { ..... }) and then pass it to the$.eachloop by doing$.each(data.items,myFunc)(Note that i only pass the name of the function without " () " after it, the$.eachloop will invoke it for you, and you can also reuse this function manually, or with more$.eachloops the same way)function (data) { ... }) which will be invoked. Inside of the implementation foreach()the function is named as the parameter toeach(). 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.