JS functions wrong output

hi everyone, I can’t understand why this code doesn’t work properly, it just gives the right answer for the first call, which is enzo but It says martin is not an admin. I’m really confused and I don’t know how to fix this. any Idea? here is my code:

    var admins = ['tania', 'martin', 'enzo'];

    function verifyUser(username) {
         
       return isAdmin(username);
        
    };

    function isAdmin(username) {
            var result ='';
        for (var i = 0; i < admins.length; i++) {
            
            if (username == admins[i]) {
         result = username + ' is an admin';
            }
            else {
                result = username + ' is not an admin';
            }
            
        }
        return result;
    }
    var enzo = verifyUser('enzo');
    console.log('enzo: ', enzo);
    var martin = verifyUser('martin')
    console.log('martin: ', martin);
    var hpc = verifyUser('hpc');
    console.log('hpc: ', hpc);

That is because you loop through the whole array of admins. The function should stop if (username == admins[i]). Since enzo is the last one it will work correctly. But in the case of martin the function will continue to loop and check if enzo (last in array) matches with martin (your input) and thus returns martin is not an admin.

So you want to use return inside the if (username == admins[i]) to ensure the function stops when an admin match is found.

1 Like

@BenGitter has already given you the correct answer, but I’d like to add my thoughts.

The reason you’re not getting the correct result is because you’re checking the whole array, and continuing to check even after finding if a user is an admit. The reason it gives you the correct result for enzo is because it’s the last item that’s being checked, so the if condition is fulfilled, and the last value stored in result is enzo is an admin. On the other hand, since martin is not the last item in the array, when checking whether he’s an admin the if condition is indeed fulfilled and the correct result is stored in result, but then on the next iteration martin is being compared to enzo, which is of course not true, so result becomes martin is not an admin and that’s what’s being returned.

I would suggest writing the function this way instead:

function isAdmin(username) {
    for (var i = 0; i < admins.length; i++) {
        if (username == admins[i]) {
            return username + " is an admin";
        }
    }

    return username + " is not an admin";
}

This way, you’re immediately returning a result once the if condition is fulfilled. If we finished iterating the array and didn’t find the username in the admins array, then this means they’re not an admin, and the return statement after the for loop takes care of that and returns to us that the user is not an admin.

Hope I’ve helped! :smiley:

2 Likes