Home > Mobile >  How do I use if statement to return -1 if what I am searching for is not in my array?
How do I use if statement to return -1 if what I am searching for is not in my array?

Time:02-01

I need to return the index place of my target and if my target is not present in my nums array I need to return -1. When I run my code it is like only my second return works?

function search(nums, target) {
    for (let i = 0; i < nums.length; i  ) {
        let exist = nums[i]
        if (exist == target) {
            return [nums.indexOf(exist)]
        } else {
            return -1
        }
    }
}

console.log(search([-1, 0, 3, 5, 9, 12], 9))

CodePudding user response:

You need to move the return -1 statement outside of the for loop

try this

function search(nums, target) {
  for (let i = 0; i < nums.length; i  ) {
    let exist = nums[i];
    if (exist == target) {
      return i;
    }
  }
  return -1;
}

console.log(search([-1, 0, 3, 5, 9, 12], 9));

  • Related