Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding Double return statement is Javascript

Tags:

javascript

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.

like image 707
Alexander Solonik Avatar asked Apr 04 '15 03:04

Alexander Solonik


2 Answers

Those "double" returns are nested within anonymous functions; they are not returning from the same context.

Working inside out:

return el2.tagId === el.tagId

is returning a boolean value from an anonymous function within the filter() method of a[i]:

a[i].filter(function (el2) {
  return el2.tagId === el.tagId
})

The length of the result of that expression is being returned within an anonymous function within the filter() method of res:

res = res.filter(function (el) {
  return a[i].filter(function (el2) {
    return el2.tagId === el.tagId
  }).length
})

Note: the length property of the result is being coerced into a boolean value by filter().

filter() is a method of the Array prototype, it constructs a new array composed of items for which the provided anonymous function returns true (see MDN: Array.prototype.filter)

like image 108
joemfb Avatar answered Sep 21 '22 10:09

joemfb


Javascript follows the functional paradigm. Think of functions as distinct bodies of code. For example, the two below are equivalent.

var sum = 0;
[1,2,3].filter(function(el) {
    return el > 2 ? true : false;
});

Is the same as

var moreThan2 = function(el) {
    return el > 2 ? true : false;
}

[1,2,3].filter(moreThan2);

Javascript uses functions to create consolidated chunks of logic. In a lot of code, javascript devs utilize anonymous function that do not get assigned to a variable.

EDITS

function common( /*…*/ ) {
    var a = arguments,

        filterListForTagsWithMoreThanOneMatchingElement = function(el) {
            function findTagsWithSameTag(el2) {
               return el2.tagId === el.tagId;
            }
            return a[0].filter(findTagsWithSameTag).length;
        },

    res = a[0]
    for (var i = 1; i < a.length; i++) {
        res = res.filter(filterListForTagsWithMoreThanOneMatchingElement);
    }
    return res
}

One thing to notice about the code is that your filter function has an internal function that relies on the closure. The closure is the scope that is created by the new function.

It seems like you are curious about the functional aspect of javascript. I would recommend a book called eloquent javascript. Unlike many javascript books it tries to focus more on the functional side of javascript. It goes into more depth than I can in this question.

like image 28
Leland Barton Avatar answered Sep 22 '22 10:09

Leland Barton