-1

I need help to rewrite some arrow functions to regular functions but right now my brain is totally stucked, I have some example code here from a rock paper scissors game I got from kyle, how would it look if I was to ditch the arrow function please somebody?

selectionButtons.forEach(selectionButton => {
    selectionButton.addEventListener('click', e => {
        const selectionName = selectionButton.dataset.selection;
        const selection = SELECTIONS.find(selection => selection.name === selectionName);
        makeSelection(selection);

would it be as easy as?:

selectionButtons.forEach(selectionButton = function() {

or have I completely lost it?

Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
Peterman
  • 9
  • 3
  • See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – jonrsharpe Nov 11 '22 at 09:15
  • @Peterman ... The OP might consider [accepting](https://stackoverflow.com/help/accepted-answer) the answer which was most helpful in solving the OP's problem. – Peter Seliger Nov 24 '22 at 12:46

2 Answers2

0
  • The list of arguments goes inside the parenthesis.
  • You need an explicit return statement
function (selection) {
    return selection.name === selectionName
}

This particular example doesn't use this but if it did it wouldn't be so simple to exchange a function expression for an arrow function (see this question).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0
// either:
selectionButtons.forEach(function (selectionButton) {
  selectionButton.addEventListener('click', function (evt) {
    // - what happens here should be prevented.
    // - one really should avoid subscribing to each element
    //   its very own ad-hoc created handler function.
    // - a shared reference of a single handler function
    //   is better in terms of resources and also of removing
    //   a listener again.
    const selectionName = selectionButton.dataset.selection;
    const selection = SELECTIONS.find(function (item) {
      return item.name === selectionName;
    });
    makeSelection(selection);
  });
});

// or:
function handleSelectionClick(evt) {
  // access currently clicked selection button from event object.
  const selectionButton = evt.currentTarget;
  const selectionName = selectionButton.dataset.selection;
  const selection = SELECTIONS.find(item =>
    // an arrow function here is much more convenient
    // than an anonymous function expression.
    item.name === selectionName
  );
  makeSelection(selection);
}
function subscribeSelectionClickHandling(selectionButton) {
  // shared reference of a one time implemented handler function.
  selectionButton.addEventListener('click', handleSelectionClick);
}
selectionButtons.forEach(subscribeSelectionClickHandling);
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37