Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 828
Augustus Brennan Avatar asked Apr 02 '26 21:04

Augustus Brennan


1 Answers

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));
like image 74
rdubya Avatar answered Apr 04 '26 11:04

rdubya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!