Q:

Finding an item's index in an array

I was writing a function that takes two arguments, an array and a number, and returns the index of the number if it's present in the array. The issue I encounter is the fact that my code returns properly without the "else" part, however, when I add the code about returning "-1" it doesn't work properly and it seems as if the compiler only takes "return -1" into account, no matter what arguments I use. Could anyone help me solve this issue?
function search(arr, item) {
for(let i=0; i<arr.length; i++){
    if(item===arr[i]){
        return i;
    }else if(item!==arr[i]){
        return -1;
    }
}
}

It's always giving me an output of "-1", when it's supposed to give the index of the "item" argument if it's presents in the first array argument.

A:

You need return -1 outside the loop so it only returns -1 if it makes it all the way through the loop without finding something. If it finds something before that, it will return the index:

function search(arr, item) {
    for(let i=0; i<arr.length; i++){
        if(item===arr[i]){
            return i;
        }
     }
     return -1;
}
console.log(search([1, 2, 3], 5))
console.log(search([1, 2, 3], 2))

