Home > other >  How to return first odd number - JavaScript
How to return first odd number - JavaScript

Time:09-10

I can't figure out how to make my code return the first odd number and if there are no odd numbers to return undefined. What am I doing wrong/need to research? The 3 requirements I have are;

1 Return the first odd number in an array of odd numbers

2 Return the first odd number when it is the last number in the array

3 Return undefined when there are no odd numbers

function firstOdd(arg){
  for (let i=0; i <= arg.length; i  ) 
  if (i % 2 !== 0) {
    return(i)
  } else {
    return undefined;
  }
}

Thank you in advanced for being kind with me.

CodePudding user response:

Take return undefined out of the loop. It's only true if none of the numbers are even. Then, make sure you test the values in the array with arg[i]. You were using the index i itself.

function firstOdd(arg){
  for (let i=0; i < arg.length; i  ) {
    if (arg[i] % 2 === 1) {
      return arg[i]
    }
  }
  return undefined;
}

console.log(firstOdd([1,3,5,7,9]))
console.log(firstOdd([2,4,6,8,9]))
console.log(firstOdd([2,4,6,8,10]))

CodePudding user response:

You can use the following code . As array starts from index 0 , so the last index of the array will be (arg.length-1).That's why I am iterating till the index is less than array length. As soon it finds odd numbers it return that and function terminates . If there is no odd number , by default the function will return 'undefined' . Hope you will understand .

function firstOdd(arg) {
  for (let i = 0; i < arg.length; i  )
    if (i % 2 !== 0) {
      return i;
    } else {
      continue;
    }
  return undefined;
}

  • Related