0

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.

2
  • 1
    yo return a value on the first iteration regardless, so you'll never get past that first iterations ... remove the else block altogether for (let i=0; i <= arg.length; i++) if (i % 2 !== 0) return i; is the whole body of the function; nothing else required, not even return undefined Commented Sep 10, 2022 at 1:39
  • off topic: you could also write function firstOdd(arg){ for(const v of arg) if(v&1) return v } Commented Sep 11, 2022 at 0:49

2 Answers 2

1

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]))

Sign up to request clarification or add additional context in comments.

Comments

0

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 arg[i];
    } else {
      continue;
    }
  return undefined;
}

1 Comment

You are returning the index, not the value of the array (i, not arg[i])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.