r/learnjavascript • • May 09 '20

Javascript Tutorial - Arrow Functions

https://www.youtube.com/watch?v=aYcH26h_HlI&t=26s
126 Upvotes

8 comments sorted by

9

u/[deleted] May 09 '20

For some reason I initially struggled to grasp arrow functions. Something about .filter(function(item) { was easier to understand for me at the time.

As with anything repetition is key. Write it enough, and you'll get it.

4

u/drumstix42 May 10 '20 edited May 10 '20

For learning the syntax, you can take it in steps to go from standard sytanx to arrow function sytanx.

Standard, multiline function

[0,1,2,3,4,5,6].filter(function(item) {
    return item > 3;
})

Remove the function portion before the parenthesis (non-valid code):

[0,1,2,3,4,5,6].filter((item) {
    return item > 3;
})

Add the arrow portion => (valid code again):

[0,1,2,3,4,5,6].filter((item) => {
    return item > 3;
})

Optionally single-line it: Remove the braces { and } and the return. The return is implied in a single line without the braces.

[0,1,2,3,4,5,6].filter((item) => item > 3)

Also note, when there is only 1 parameter, the parenthesis are optional. E.g.:

[0,1,2,3,4,5,6].filter(item => item > 3)

But if there are no parameters, or more than 1, the parenthesis are required.

12

u/Content_Performer May 09 '20

TL:DR functions but 'this' actually works

3

u/gotta-lot May 10 '20

I really don’t like when it’s described this way. In JavaScript, ‘this’ has a clear set of rules. It just behaves differently with arrow functions. They serve a very different purpose. Given the way we write JavaScript in 2020, maybe we favor the way it behaves with arrow functions, but I still think it’s unfair to say ‘this’ in function expressions and declarations is something that is broken.

1

u/43northwebdesign May 09 '20

What ide is this

2

u/ddmanton7220 May 09 '20

It's a website. playcode.io

1

u/43northwebdesign May 09 '20

Oh cool thanks

1

u/bajcmartinez May 22 '20

great video, I've written an article with the don'ts of arrow functions, for those interested:

https://medium.com/@bajcmartinez/when-not-to-use-javascript-arrow-functions-a7340630d4a8

or in my personal site for those who don't have medium accounts:

https://livecodestream.dev/post/2020-05-22-when-not-to-use-javascript-arrow-functions/