Home > Software design >  How to write Java Script arrow functions in regular function syntax?
How to write Java Script arrow functions in regular function syntax?

Time:11-11

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?

CodePudding user response:

  • 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).

CodePudding user response:

// 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);
  • Related