Augustus Brennan Augustus Brennan - 1 month ago 19
Javascript Question

Simple Q Javascript - Why does this return false?

Why does this return false? I would think the for loop should encounter the first 3, satisfy the if conditional and then return true. Thanks for any help.



var array = [3, 3, 0, 0, 0, 3, 3];

function some(array) {
for (var i = 0; i < array.length; i++) {
if (array[i] == true) {
return true;
}
}
return false;
};

console.log(some(array));
// false




Answer

It returns false because you are comparing to true and none of the values in your array are true or 1 (which javascript considers to be true). If you modify your check to just check the truthiness of the values then you would get the value you expect.

var array = [3, 3, 0, 0, 0, 3, 3];

  function some(array) {
    for (var i = 0; i < array.length; i++) {
      if (array[i]) { //Notice we just check for a truthy value
        return true;
      }
    }
    return false;
  };

  console.log(some(array));