Tony Sparda Tony Sparda - 7 months ago 51
Javascript Question

When using x as index no. to show array location in a funtion, the array returns undefined

Hi guys so my function is returning undefined when I am using x to represent the index number of an array in the below code, why is this happening?
It would be very much appreciated if somebody could answer my question

var a = 0;
var b = 0;
var z = 0;
var x = 0;
function findOutlier(integers){
//your code here
while(x < integers.length){
if(integers[x]%2 === 0){
a = x;
z = z + 1;
b = x;
x = x + 1

if(z === 1){return integers[a]}
else{return integers[b]}



x <= integers.length The array goes from 0 to length-1, so looping from 0 to length means you are going one off the end of the array.

Replace with while(x < integers.length).