-1

I am working on a simple function that should return the first element of an array that matches my criteria using a for loop. It keeps returning the first element of the array whether it meets the set criteria or not. Any idea where the bug is here? I also tried the .find() method, same issue.

function wheresTheBeef(array) {
  for (var i = 0; i < array.length; i++) {
  if  (array[i] == 'fillet' || 'strip' || 'sirloin') {
      return array[i];
    }
    else {
      return 'there is no beef!'
    }
  }
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
N00b_Overflow
  • 53
  • 1
  • 2
  • 9

4 Answers4

1

Your condition is incorrect, change this:

if  (array[i] == 'fillet' || 'strip' || 'sirloin') {

for this one:

if  (array[i] == 'fillet' || array[i] == 'strip' || array[i] == 'sirloin') {

Reason of the change:

let var1="something";

if (var1) {
  console.log("var1 has a truthy value");
}

if (1==0 || "something") {
  console.log("condition is true");
}
Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
1

You need to test each element with the string, because every single non empty string is truthy.

if (array[i] === 'fillet' || array[i] === 'strip' || array[i] === 'sirloin') {

Nearly the same with Array#find and Array#includes

found = array.find(item => ['fillet', 'strip', 'sirloin'].includes(item));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

so you just need to get rid of the second return statement (and the else). As soon as you return, execution will stop. So if you never return, the loop will continue until it is satisfied.

If you still need the there is no beef statement, you can put it outside the loop. If the loop executes and the condition is never satisfied, then it will proceed to return that statement.

wilsonhobbs
  • 941
  • 8
  • 18
0

There are 2 problems here.

  1. Your if checking is wrong, because array[i] == 'fillet' || 'strip' || 'sirloin' will always TRUE

  2. And you should not return directly in else branch, otherwise your code logic is only checking for first element

function wheresTheBeef(array) {
  for (var i = 0; i < array.length; i++) {
  if  (array[i] == 'fillet' || array[i] == 'strip' || array[i] == 'sirloin') {
      return array[i];
    }
    else {
      continue
    }
  }
  return "there is no beef"
}
yue you
  • 2,206
  • 1
  • 12
  • 29