DEV Community

zmiles17
zmiles17

Posted on

Arrow Functions

I haven't used arrow functions at all in my journey through JavaScript, but I was introduced to the idea that arrow functions carry over or bind the value of "this". Before ES6, web developers had to bind "this" by setting it equal to a variable or by using the "bind" method. Here is an example of a function I used in one of my homework assignments.

A submit listener without an arrow function

It's just a basic event listener that will fire once the user submits the form. The only thing I want you to take note of is the value of "this" inside the initial function and after the ".then(function ()".

As you can see, "this" has different definitions. If we want the value of "this" to carry over to the next function, then we can simply change ".then(function ()" to ".then(() =>". I won't show the change in the code to avoid redundancy, but I want to demonstrate that "this" will now be equal to what "this" was in the containing function.

Arrow functions also do not require you to use the return keyword, or use parenthesis if only using one parameter.

If we needed more than one parameter, then parenthesis are required.

TL;DR

Arrow functions bind the value "this", implicitly use the "return" keyword, do not require parenthesis if only using one parameter, and make our code much more concise and easier to read. One thing to note is that once you use an arrow function, you cannot unbind the value of "this" inside of that function. For general use, it is better to use "function" in the global scope and avoid using arrow functions as constructors!

Top comments (0)