fields fields - 9 months ago 24
Javascript Question

Javascript: For Loop, need help understanding this exercise with if/else

I have this exercise that already got the answer, but after hearing the explanations, still don't understand. This is the exercise:


"write a function isUniform() which takes an array as an argument and
returns true if all elements in the array are identical"


This is the solution

function isUniform(numArr) {
var first = numArr[0];
for (var i = 1; i < numArr.length; i++) {
if (numArr[i] !== first) {
return false;
}
}
return true;
}


I got it almost right, but i did a else statement with the "return true" and it didn't work. Why does it work with the "return true" outside of the for loop?
(edited) This is how i did the first time:

function isUniform(numArr) {
var first = numArr[0];
for (var i = 1; i < numArr.length; i++) {
if (numArr[i] !== first) {
return false;
}
else {
return true;
}
}
}

Answer Source

If you return true outside the loop, then it checks every element in the loop until one matches the if test or it gets to the end of the loop.

If you return true inside the loop then it will always hit a return statement for the first element and then stop the loop.