What does the "=>" operator mean?

Asked

Viewed 2,921 times

23

I was seeing some solutions in Javascript and in one case I saw this command line: return args.reduce((s, v) => s + v, 0);. But I don’t know what the operator means =>.

What is his function?

2 answers

25


Is known as Arrow functions.
One Arrow Function is exactly like a normal/callback function, only less verbose and instance references like this are taken from the "surroundings" (which avoids .bind() or those var that=this).

So:

var numbers = [1,2,3];
squares = numbers.map(x => x * x);

which is equivalent to:

squares = numbers.map(function (x) { return x * x });

I don’t want to write an extensive response with all the details because it’s redundant. There’s so much about it out there that’s not worth the effort. As an example, here is EXCELLENT content on this:

http://exploringjs.com/es6/ch_arrow-functions.html

  • 2

    Good answer but, about your comment at the end, I think that even having a lot of content available elsewhere, it is always worth adding as much detail and information as possible in your reply. Especially if most of the external content is in English.

  • 5

    @Gabe I disagree. This is more valid for subjects that are barely addressed and with little content. Here at Sopt there is a very strange culture of being too redundant and writing answers so long and boring when all it takes is just a direct answer. This is exactly the case here: There is excessive content on the subject out there.

  • 4

    @felipsmartins agree in parts, but what Gabe said was not to write a "long answer" but perhaps to put in the most direct beginning and separate a sub-topic for other details that may be interesting, no one said it is mandatory, this is just a hint, since the link is in English. Understand as a constructive criticism and not a requirement, the answer is already great the way this +1.

10

This is a function lambda, or as it is often called, arrow function. Is a anonymous function with a simpler syntax. available since Ecmascript 6.

The left parentheses are the parameters and the one on the right is the body of the function that is already the expression that generates the result that will be returned in the function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.