Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does addEventListener e=> mean?

Tags:

javascript

I am trying to learn the base of this code, but I don't understand the meaning of the e=>. I guess that it's some kind of a shortcut, and I've done some research and didn't find anything. I want to make the most out of this code. So can you help me, or at least not devote? What is this syntax?

const scriptURL = 'https://script.google.com/macros/s/AKfycbzslEnJtPfNT6z0ohrXP9cZYGhWvKVsFjQV7eLcriT3tok5D5ty/exec'
const form = document.forms['submit-to-google-sheet']
form.addEventListener('submit', e => {
  e.preventDefault()
  fetch(scriptURL, { method: 'POST', body: new FormData(form)})
  .then($("#form").trigger("reset"))
  .catch(error => console.error('Error!', error.message))
})
like image 876
Lavi Arzi Avatar asked Feb 28 '26 07:02

Lavi Arzi


2 Answers

e => {
    e.preventDefault();
}

is equivalent to

function (e) {
    e.preventDefault();
}

... In this specific example

form.addEventListener('submit', e => { e.preventDefault(); ... });

e is the eventObject, which the event was triggered by.

form.addEventListener('submit', eventObj => { eventObj.preventDefault(); ... });
like image 91
safwanmoha Avatar answered Mar 01 '26 21:03

safwanmoha


This is an arrow function:

e => {}

is the the es6 way of declaring functions/closures.

In most cases it can be used interchangeably with:

function(e){}

But there are some differences, mainly with the lack of binding to this, so use with caution if you are expecting them to work in the same way when using this in your functions (ie: prototype functions).

like image 45
Miroslav Glamuzina Avatar answered Mar 01 '26 19:03

Miroslav Glamuzina