Tony Sparda - 3 months ago 9

Javascript Question

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

Code:

`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;

}

else{

b = x;

}

x = x + 1

}

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

else{return integers[b]}

}

findOutlier([2,6,8,10,3]);

Answer

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

.

Source (Stackoverflow)

Comments