So the return true
isn't returning a value for the function isUniform
, it's returning a value for the callback that you provided to the forEach
method. forEach
is really only used to create side effects. So forEach
executes the callback on each element, sees that the callback returns false
, but then doesn't have anything to do with that value, so it throws it out and moves on to the next element in the array. After iterating through the array, it moves on to the next line of code and returns true
for the function.
One way that you might do this using forEach
is to declare a variable that you initialize as true and manipulate that within the callback. This is necessary, as there's not a way to end the execution of a forEach
loop early. So you might instead use:
function isUniform(myArray) {
var passing = true;
myArray.forEach(function(element) {
if (element !== myArray[0]) {
passing = false;
}
});
return passing;
}
Or you could use a for
loop or a for-of
loop, in which case the return
statement would work as you had originally expected. You're probably already familiar with for
loops. For-of
loops were introduced in ES2015 (so they might not work on all JS engines). A for-of
loop would look like this:
function isUniform(myArray) {
for (element of myArray) {
if (element !== myArray[0]) {
return false
}
}
return true
}
However, the best way to do this is probably using the built in array method every
, which returns true
if every element in the array passes the test provided in the callback. So you might test every element to see if they're equal to the 0th element in the array and thus equal to each other:
function isUniform(myArray) {
return myArray.every(function (currentElement,index,array) {
return currentElement === array[0]
})
}
That's short enough that you really don't even need to put it in its own function -- and your code will probably be more readable if you don't.
Docs:
Array.prototype.every: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
For-of loop: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of