I wanted to understand in depth why this works
[0, 1, 2].map(i => i + 1)
but this doesn't
[0, 1, 2].map(i => {i + 1})
I had this problem when I was working on a jQuery script. I tried to use a map with an arrow function to extract $(this).data('id')
from checkboxes and we got an array of undefined. About an hour later by pure luck we copy pasted some stack code and notices the only difference was the function() {}
so now i'm wondering why? Is it bad to use arrow functions? is it not patible?
For the record I am using Google Chrome Version 66
I wanted to understand in depth why this works
[0, 1, 2].map(i => i + 1)
but this doesn't
[0, 1, 2].map(i => {i + 1})
I had this problem when I was working on a jQuery script. I tried to use a map with an arrow function to extract $(this).data('id')
from checkboxes and we got an array of undefined. About an hour later by pure luck we copy pasted some stack code and notices the only difference was the function() {}
so now i'm wondering why? Is it bad to use arrow functions? is it not patible?
For the record I am using Google Chrome Version 66
Share Improve this question asked May 12, 2018 at 0:44 Raid55Raid55 951 gold badge2 silver badges7 bronze badges 3-
2
{return i+1}
... it's part of the syntax() => { statements }
- if you want to return something inside{}
you have to explicitly return it ... fact is the code you posted that works is the "shorthand" (advanced syntax) version of arrow notation - developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Jaromanda X Commented May 12, 2018 at 0:46 - 2 ^, arrow functions without braces have an implicit return. – Ry- ♦ Commented May 12, 2018 at 0:47
-
2
Is it bad to use arrow functions? is it not patible?
No, it's not bad nor inpatible assuming you've done the bare minimum reading on how arrow functions work... – VLAZ Commented May 12, 2018 at 0:57
2 Answers
Reset to default 12Its an ES6 arrow function syntax difference. Add a 'return' and you will get the response [ 1, 2, 3 ]
[0, 1, 2].map(i => {return i + 1})
Reference : https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Thanks
There are a couple of syntaxes for arrow functions https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
The first one has an implied return of the expression value. The syntax with { ... } doesn't, so you need to supply it explicitly.