2

What is the difference (if any) between:

$('.title').click(e => {
    do_something();
});

and this one:

$('.title').click(function(e) {
    do_something();
});
Yahya Essam
  • 1,832
  • 2
  • 23
  • 44
  • The first is an arrow function. The main difference is that an arrow function maintains the enclosing scope. It's also completely unsupported in IE. You can read more at [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) – Rory McCrossan Oct 24 '18 at 11:02
  • https://stackoverflow.com/questions/27670401/using-jquery-this-with-es6-arrow-functions-lexical-this-binding – Mohammad Oct 24 '18 at 11:02

1 Answers1

4

this is the same but this arrow function is a new syntax stating fro es6.
please refer to MDN to get more information about arrow functions :

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Arrow functions (also called “fat arrow functions”) are undoubtedly one of the more popular features of ES6. They introduced a new way of writing concise functions.

Here is a function written in ES5 syntax:

function timesTwo(params) {
   return params * 2
}

Now, here is the same function expressed as an arrow function:

var timesTwo = params => params * 2

It’s much shorter! We are able to omit the curly braces and the return statement due to implicit returns (but only if there is no block — more on this below).

It is important to understand how the arrow function behaves differently compared to the regular ES5 functions.

No parameters If there are no parameters, you can place an empty parentheses before =>.

() => 42

In fact, you don’t even need the parentheses!

_ => 42

Single parameter With these functions, parentheses are optional:

 x => 42  || (x) => 42

Multiple parameters Parentheses are required for these functions:

(x, y) => 42

Statements (as opposed to expressions) In its most basic form, a function expression produces a value, while a function statement performs an action.

With the arrow function, it is important to remember that statements need to have curly braces. Once the curly braces are present, you always need to write return as well.

Here is an example of the arrow function used with an if statement:

var feedTheCat = (cat) => {
  if (cat === 'hungry') {
    return 'Feed the cat';
  } else {
    return 'Do not feed the cat';
  }
}

“Block body” If your function is in a block, you must also use the explicit return statement:

var addValues = (x, y) => {
  return x + y
}

Object literals If you are returning an object literal, it needs to be wrapped in parentheses. This forces the interpreter to evaluate what is inside the parentheses, and the object literal is returned.

x =>({ y: x })

another thing for jquery. you better use .on insteed of .click

for more info refer to :
Difference between .on('click') vs .click()

Yahya Essam
  • 1,832
  • 2
  • 23
  • 44