Younghun Jung
Younghun Jung

Reputation: 361

How can I fix 'Refactor this function to use "return" consistently.' from sonar js

I apply SonarJS analysis to my project. An error 'Refactor this function to use "return" consistently' was found in the code below. How can I fix this?

var filter1Depth = function(attr0, attr1, val){
        var id;
        if(val === "vAuto"){
            id = "AirConditioner.Indoor.Ventilator";
            val = "Auto";
        }
        return { // Error is generated from this line.
            field : attr0,
            operator: function(item, value){
                if(value == "") return true;
                if(!item || !item.length) return;

                var i, length = item.length;
                if(value == "undefined"){
                    for( i = 0; i < length; i++ ){
                        if(typeof item[i][attr1] === 'undefined'){
                            return true;
                        }
                    }
                }else{
                    for(i = 0; i < length; i++){
                        if(item[i][attr1] == value){
                            if(id){
                                 if(id === item[i]["id"]) return true;
                                 return;
                            }
                            return true;
                        }
                    }
                }

                return;
            },
            value : val
        };
    };

Another example is like below.

var filter1DepthNone = function(attr0, attr1, val){
        return { field : attr0, operator: function(item, value){ // error!!
            if(value == "") return true;
            if(!item || !item.length) return;

            var length = item.length;
            for(var i = 0; i < length; i++){
                if(item[i][attr1] != value){
                    return;
                }
            }

            return true;
        }, value : val};
    };

My codes where this error is generated from has similar pattern..

Upvotes: 0

Views: 4032

Answers (1)

KLP
KLP

Reputation: 433

In some blocks, you're returning nothing (return;, so undefined) but in other blocks in the same function, you return a boolean (true/false).

You need to make sure that your returns are consistent within a function - that is, if you return a boolean somewhere, everywhere you return a value within that same function, you also return a boolean.

Upvotes: 1

Related Questions