0

hopefully someone will be able to help me solve this issue that I'm dealing with. I am trying to return a function inside a function but my code seems not to work... using Javascript. Here is my code :

function chosenPiece() {
  if (isWhite) {
    for (let i = 0; i < 12; i++) {
      whitePiecesList[i].addEventListener("click", function findPositionOnBoard(event) {
        for (let i = 0; i < boardCellsList.length; i++) {
          if (boardCellsList[i].firstElementChild === event.target) {
            let position = i;
            return position;
          }
        }
      });
    }
  } else {
    for (let i = 0; i < 12; i++) {
      blackPiecesList[i].addEventListener("click", function findPositionOnBoard(event) {
        for (let i = 0; i < boardCellsList.length; i++) {
          if (boardCellsList[i].firstElementChild === event.target) {
            let position = i;
            return position;
          }
        }
      });
    }
  }
  return findPositionOnBoard();
}

Can someone identify the problem? Thanks!

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • Using `return` inside envent listeners doesn't make sense. That value can't be used. – Maheer Ali Dec 09 '20 at 17:40
  • "*my code seems not to work*" what's the problem? Do you get an error? Do you get the wrong output? What's the expected input and output for this? – VLAZ Dec 09 '20 at 17:40
  • Super nitpicky. Why do you need a `position` variable? Just return `i` – Taplar Dec 09 '20 at 17:41
  • You can return a reference to a function by omitting the parentheses in the return statement. Adding parentheses actually executes the function and returns the function's return value – Ted Dec 09 '20 at 17:43
  • where do you get `boardCellsList` from? – Nina Scholz Dec 09 '20 at 17:44
  • The scope of the name in a named function expression is just the body of the function. So you can't refer to `findPositionOnBoard` outside those functions. You need to declare the name in the `chosenPiece` function body, then assign it before returning it. – Barmar Dec 09 '20 at 17:44
  • The `chosenPiece` function is running now. It can't return a value *after* a button is clicked because that won't happen until the future. – Quentin Dec 09 '20 at 17:44
  • But it's not clear why you would want to return the function that's being used as an event listener in the first place. Do you need it so you can call `removeEventListener()` later? – Barmar Dec 09 '20 at 17:45

0 Answers0