0

So while trying to set up a new function that I needed to search though a array and return the index if it found a match. I came across something weird and havent been able to find a explanation. For some reason the return inside the forEach does not leave the function allowing the second return to return null.

function findRoomByName(name) {
    let index = 0;
    roomStatus.forEach(e => {
      if(e.name == name){
        return index
      }
      index++
    });
    return null
  }

I have fixed the problem with this code but I want to know why this is happening and if there is a better approach then this. Thank you

  const FindRoomByName = (name) => {
    let index = 0;
    let hit = false
    roomStatus.forEach(e => {
      if(e.name == name){
        hit = true
        return index
      }
      index++
    });        
    if(hit){
      return index
    }
    else{
      return null
    }
  }
Clue Less
  • 47
  • 8
  • 1
    `return` applies to the enclosing function. The enclosing function of your `return` is the `e => { ... }` arrow function. – Ivar Oct 20 '22 at 14:23
  • 2
    If you want to return from the overall function from within a loop then use a loop, not `forEach`. – David Oct 20 '22 at 14:25
  • 1
    Any time you use `=>` you are writing an [arrow function expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). It creates a function, albeit an anonymous arrow function. Any return statement within the scope of that arrow function is a return from the arrow function itself, not from the outer function that invokes the arrow function. – jarmod Oct 20 '22 at 14:26

0 Answers0