I am trying to write a function that returns the first odd number in an array.
I have this so far but it is returning undefined.
function findFirstOdd(numbers) {
let oddNumbers = [];
for (let i = 0; i <= numbers.length; i++) {
if (numbers[i] % 2 != 0) {
oddNumbers.push(numbers[i])
} else {}
};
return oddNumbers[0]
};
console.log(findFirstOdd(6, 2, 9, 3, 4, 5));
I would expect this to return 9; being the first odd number.
4
Answers
Your function call is wrong, numbers should be in array.
Your code expects to receive an array as argument, but you are passing multiple numbers, not an array.
There are two simple ways to solve this:
OR
Also, one suggestion, you can remove empty
else
+ you may return first odd number right after you found itFull code:
UPD:
After you learn array methods, you can upgrade it to:
numbers
parameter most be an array:I cleaned your script into this:
I change some sections in your code:
I changed entry of function into an array:
var numbers = [6, 2, 9, 3, 4, 5];
for(let i = 0; i <= numbers.length; i++)
tofor(let i = 0; i < numbers.length; i++)
return oddNumbers[0]
toreturn oddNumbers;
semicolon
;
on javascript codes are not necessary.JavaScript functions arguments can only relate to a single variable.
In your case you have 2 choices:
...
)Rest parameters usage:
keyword
arguments
usage:PS: one line code ( odd numbers right bit have a binary value === 1 )