There are so many ways to get stuff done in web development. You have functions, callback functions, methods, arrow functions, and all the other functions out there. The focus for this little explanation are the arrow functions because they're relatively new.
Arrow functions became a thing when EcmaScript6 (ES6) was released. They are really similar to regular functions except for a few things. First of all, the syntax for writing an arrow function is a lot more compact than a regular function. Here's what I mean:
Regular function
function getPrice(cost, quantity) {
return cost * quantity;
}
Arrow function
(cost, quantity) => cost * quantity;
With arrow functions, you don't have to write nearly as much code and you get the same results. There's more to it than that of course. A big thing is that arrow functions don't bind to the keyword this and that's not necessarily a bad thing. You can actually use the this that is bound to the code that contains the arrow function and that's pretty nice.
Arrow functions are really flexible too. You can use them with or without parameters. So if you only need one parameter, you can use an arrow function one of these ways:
(day) => 5;
day => 5;
The parenthesis in this case are optional. Or if you don't need any parameters you can use the arrow function one of these ways:
() => "Candy";
_ => "Candy";
Another thing to keep in mind is that you still have to follow the code block rules of functions. If you have more than one statement you need the function to execute, you still need to use curly braces like this:
() => {
let x = 7;
let y = -23;
return x * y;
}
I need to caution you with using arrow functions. Since they are anonymous functions (they don't have function names), it can be harder to debug your code. Tracing your way through the call stack might not get you to the root of the problem if you have a bunch of arrow functions.
The main time you want to use these is when you don't want to bind to this. If you know that you'll need to work with this from a different context, arrow functions are the most beautiful things to work with.
That's my quick breakdown of arrow functions. I hope it helped you out! If you have anything to add or a question, just let me know in the comments.
Hey! You should follow me on Twitter because reasons: https://twitter.com/FlippedCoding
Top comments (2)
I love them, they make the code cleaner, and the binding to external this is super nice in React classes because otherwise you have to do it manually in the constructor.
I always think of this (ES2018) April fools video whenever someone says "x makes my code much cleaner"
youtube.com/watch?v=s-G_RZ4RJLU