1

This line in an exiting project is giving me syntax error

document.querySelectorAll('[name="callqualitycheck"]').forEach(e=> {
  if(e.checked){comment = comment + "," + e.value;}
});

When I change forEach(e=> { to forEach(function(e) {. Its working fine. But I am not sure what is the difference and it will not create any problem in future. Can anyone explain this?

Y2H
  • 2,419
  • 1
  • 19
  • 37
Yasir Ijaz
  • 674
  • 1
  • 12
  • 19
  • 2
    The => is an ES2015 feature. It is an arrow function. It does the same thing as function() except that the this value is passed down to any inner methods meaning you don't need to bind any this values to your function. More information here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Jackthomson Oct 26 '17 at 07:28
  • 2
    Arrow function syntax `=>` is newer. Where are you trying to run this? In a browser? Does the browser understand the new syntax? Take a look at the browsers section of this article https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – mortb Oct 26 '17 at 07:29

2 Answers2

2

forEach(e => { code }) and forEach(function(e){ other code }) can perform the same task, however they are not equivalent per se.

The first one uses the new arrow function introduced in ECMA6. Arrow functions capture the outer scope’s this (i.e. when you use this it refers to the the scope of the function containing it.) Regular functions however have their own this. The fact that arrow functions do not have their own this is actually one of the reasons why it was introduced. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)

The second difference is that you cannot bind an arrow function.

Another difference arises in strict mode. Given that this comes from the surrounding lexical context, strict mode rules with regard to this are ignored by arrow functions.

So while you can basically perform the same task using either of them, one might be more convenient than the other depending on your case.

Y2H
  • 2,419
  • 1
  • 19
  • 37
  • 2
    They are not equivalent - there are key differences. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Ant P Oct 26 '17 at 07:33
  • 3
    They are **not** equivalent! Arrow functions capture the outer scope's `this`, while regular functions will have their own `this`. In the OP's code that makes no difference but the functions are not equivalent. Also, you cannot `.bind()` an arrow function. – Robert Rossmann Oct 26 '17 at 07:33
-1

You don't need the brackets { } in a lambda function. You can for example do it with a ternary operator.

document.querySelectorAll('[name="callqualitycheck"]').forEach(e=>
  comment += e.checked?','+e.value:'');
zruF
  • 50
  • 8