J. Doe
J. Doe

Reputation: 11

return value to the function from outside

I'm comparing couple info and than try to get the correct object. But I cant return the output to the function it self.

    channelUserRight: function(channel, nickname){

        userlist.forEach(function(chaninfo) {
            if(chaninfo.channel === channel && chaninfo.name === nickname){
                // Whenever I do console.log it shows me output
                console.log(chaninfo);
                return chaninfo;
            }           
        }); 

    }
// Here it shows me 'undefined'
console.log(channelUserRight(channel, user))
channelUserRight(channel, user)

So inside the function I get the correct object but not outside the function.

Upvotes: 0

Views: 43

Answers (2)

adeneo
adeneo

Reputation: 318312

You're just return to the callback for the forEach function, if you use filter instead, you can return the filtered array, or just the first index directly

channelUserRight: function(channel, nickname){
    var list = userlist.filter(function(chaninfo) {
        return chaninfo.channel === channel && chaninfo.name === nickname;
    });

    return list.length ? list.shift() : null;
}

Upvotes: 3

tadman
tadman

Reputation: 211690

In this situation you need to set a variable at the function level and use that to return your value:

function(channel, nickname){
  var _chaninfo;

  userlist.forEach(function(chaninfo) {
     if(chaninfo.channel === channel && chaninfo.name === nickname) {
        _chaninfo = chaninfo;
     }
  }); 

  return _chaninfo;
}

The problem is that return returns from the function block used to iterate. @adeneo's approach with filter is actually cleaner, so I'd recommend using that, but this is a "fix" for your immediate issue.

Upvotes: 1

Related Questions