Federico
Federico

Reputation: 13

Why does this Javascript function always return true?

I built a function every that should iterate over an array and return true if the action (for ex. element < 10) performed on all the elements is true. Here's my code:

function every(array, action) {
  var trueOrFalse = true
  for (var i = 0; i < array.length; i++)  
    trueOrFalse = trueOrFalse && action(array[i]);
  if (trueOrFalse = true) return true;
  else  return;
}
array1 = [1,2,3,4,5,6,7,8,9,10,11]
console.log(every(array1, function(element) {
  return element < 10 
}))

I don't see anything wrong. With array1 it returns true even if it contains numbers > 10. Where's the problem?

Thanks

Upvotes: -1

Views: 1862

Answers (4)

Cameron Wilby
Cameron Wilby

Reputation: 2310

You can remove the if statement and rely on good old boolean algebra!

function every(array, action) {
  var trueOrFalse = true
  for (var i = 0; i < array.length; i++)  
    trueOrFalse = trueOrFalse && action(array[i]);
  return trueOrFalse;
}
array1 = [1,2,3,4,5,6,7,8,9,10,11]
console.log(every(array1, el => el < 10));

Upvotes: 0

Mr Mystery Guest
Mr Mystery Guest

Reputation: 1474

You need to evaluate trueOrFalse is equal to true For which you need the double equals

if (trueOrFalse == true) return true;

Other wise you'll just be making the value of trueOrFalse the same as true

Bonus points:

 if (trueOrFalse === true) return true;

Using three equal signs is evaluating exactly the same type and value. That isn't required here but is useful to know.

Upvotes: 1

Master Yoda
Master Yoda

Reputation: 4402

Your condition is using an incorrect operator, you should be using the == operator.

You can use if (trueOrFalse == true) return true;

OR

you can write it as if (trueOrFalse) return true; which will still evaluate it as if( true )

Upvotes: 0

mika
mika

Reputation: 1451

if (trueOrFalse = true) return true; 

should be

if (trueOrFalse == true) return true;

Upvotes: 4

Related Questions