Trying to learn JS and I came across an issue while implementing a function thats supposed to return the biggest number in an array.
const array2 = ['a', 3, 4, 2] //Supposed to return 4 according to the tutorial im watching
function biggestNumberInArray(arr) {
let i = arr[0];
for(item of arr){
if(i < item) i = item;
}
return i;
// returns 'a' instead of 4
}
When passing array2 into the function, instead of returning 4 it returns 'a' and Im pretty sure thats because the ascii value of 'a' is higher than 4. So my question is, is there a way to check the types of the elements of an array as im iterating through them? If not, what would someone do if they had an array of different types and they had to compare the elements in the array to each other like?
Also, I found out that instead of initializing i
to arr[0]
and instead initializing it to 0
instead, that it will return 4 instead of 'a'. Why is that?