0

I am new to javascript and jQuery and am trying to understand events better.

Is there an ideal time to use function(event) {} vs. (event => {}? Can you do the same things with either and it's a tomayto tomahto type thing or are there certain instances you need to use one or the other? Is one a declaration and one and expression? It seems like one isn't a function but you can run functions in the curly brackets?

for example:

.mousedown(function(event) { });

VS.

.mousedown(event => [code]);

Can a normal function() ever accomplish things in this realm?

Thank you very much!

  • 1
    `function(event) {} vs. function(event => {}` they are two very different things ... one is a function, the other is invalid syntax - if the second was meant to be just `event => {}` then, they are similar, but still not interchangeable - see arrow function documentation – Jaromanda X Mar 17 '20 at 01:09
  • 1
    are you asking what the difference is between `.methodName(function(event) {})` and `.methodName(event => {})` is? If so, the difference is to do with functions and arrow functions which is described here: [Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?](https://stackoverflow.com/q/34361379) – Nick Parsons Mar 17 '20 at 01:11
  • @NickParsons exactly, yes. This is extremely helpful, thank you very much! – coder_person123 Mar 17 '20 at 01:15

1 Answers1

0

In the case you presented, calling an event, I'd use the arrow function, because it's not something your going to callback, it triggers with the event.

Regular functions are commonly used for whenever you need to call them by their name and arrow functions simplify for something you don't need to name or want to do it quicker and cleaner. They are similar, but there are actually important differences between them and I'll leave you a short article about those:

https://medium.com/better-programming/difference-between-regular-functions-and-arrow-functions-f65639aba256

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459