I am new to JS and basically learning new stuff everyday, I am just learning things like , how to dynamically update an array and stuff. Anyways, I usually try to pick up clean JS snippets of the net and debug them, till I get the hang of what it really means. So here is a snippet that I found today:
var array1 = [
{ tagId: 1, tagName: 'tag 1' },
{ tagId: 2, tagName: 'tag 2' },
{ tagId: 3, tagName: 'tag 3' },
{ tagId: 4, tagName: 'tag 4' }
];
var array2 = [
{ tagId: 1, tagName: 'tag 1' },
{ tagId: 2, tagName: 'tag 2' },
{ tagId: 8, tagName: 'tag 8' }
];
var array3 = [
{ tagId: 1, tagName: 'tag 1' },
{ tagId: 0, tagName: 'tag 0' },
{ tagId: 9, tagName: 'tag 3' },
{ tagId: 12, tagName: 'tag 12' },
{ tagId: 13, tagName: 'tag 3' },
{ tagId: 14, tagName: 'tag 2' },
{ tagId: 6, tagName: 'tag 6' },
];
var a4 = common(array1, array2, array3)
console.log(a4);
function common( /*…*/ ) {
var a = arguments;
res = a[0]
for (var i = 1; i < a.length; i++) {
res = res.filter(function (el) {
return a[i].filter(function (el2) {
return el2.tagId === el.tagId
}).length
})
}
return res
}
Basically the snippet suns through arrays with object literals in them and filters them out. Now, here is my question. Being a newbie to JS, I have come across the interesting case of seeing alot of JS code use the return statement in quick succession, or rather one after another. Often they are nested , this is a very interesting case to me, because usually I guess a single return statement should be all one needs.
Anyways, back to my example and what my difficulty really is, if you see the code inside the common function , you will see the below code:
res = res.filter(function (el) {
return a[i].filter(function (el2) {
return el2.tagId === el.tagId
}).length
})
I really fail to understand the double return statements. What I understand is, return el2.tagId === el.tagId returns true or false and return:
a[i].filter(function (el2) {
return el2.tagId === el.tagId
}).length
It returns the length, which I think should be an integer, but whats the order of the return execution? Who is return el2.tagId === el.tagId returning to?
I am always perplexed when I see the double return statements. Can somebody explain this to me please?
Jsfiddle here.
EDIT :: try and be a bit elaborate in your answer .
Thank you.
Alex-Z.