...
JavaScript Arrow Functions 5 Smart Ways

JavaScript Arrow Functions: 5 Smart Ways

Learning how to create JavaScript arrow functions are an incredibly important skill to learn in order to write modern, readable and maintainable code.

In 2015 ECMAScript introduced arrow functions. These were designed to provide a shorter way to define functions while at the same time providing a solution to two long standing issues of “this” behavior.

You may already be creating regular functions using the function keyword. Arrow functions are very similar to regular functions yet they are fundamentally different. They do not simply represent a style preference; they change how your code behaves under specific conditions.

Understanding when and how to utilize JavaScript arrow functions will enhance your abilities as a developer. Let us discuss five critical concepts that you will need to understand in order to effectively utilize arrow functions in your project development.

1. The Syntax: Smaller, Simpler Functions

Perhaps the first thing you notice about arrow functions compared to regular functions is the syntax. Where you previously used the function keyword you now use the fat arrow => between the parameters and the function body.

A regular function could look something like this: function add(a,b){return a+b;} An arrow function can be as simple as: (a,b)=>a+b; No function keyword, no curly brackets, no return statement needed when the function is simple enough.

It is particularly beneficial for smaller, single purpose functions. If you are going to pass a function to map(), filter(), or forEach() arrow functions greatly decrease the amount of visual clutter created by your code.

There are numerous ways to format arrow functions. There is the option of using empty parenthesis if there are no parameters: ()=>42;. Using a single parameter allows you to exclude the parenthesis: x=>x*2;. However, when there are multiple parameters you must include the parenthesis: (a,b)=>a+b;.

When the function body contains multiple lines of code then you enclose the function body within curly brackets and explicitly state the return: (a,b)=>{let result=a+b;return result;}.

2. Implicit Returns: A One-Line Super Power

One of the most popular aspects of arrow functions is implicit returns. When you create an arrow function containing only one line of code and do not encase it in curly brackets, whatever value that line produces will automatically be returned as part of the function. You do not require a return statement.

Implicit returns are extremely helpful for transformation functions. As an example, numbers.map( n => n * 2); will produce an array where every number was multiplied by 2. The arrow function implicitly produced n * 2 as the return value.

In order for an arrow function to return an object literal without requiring an explicit return, it must be enclosed in parenthesis: ()=>({name:’Alice’}).

Implicit returns allow developers to significantly increase readability of functional programming patterns. Take a comparison of arr.filter(function(item){return item>10;}); and arr.filter(item=>item>10);. The second example utilizes an arrow function and is cleaner and allows developers to focus more clearly on what the logic being applied is doing rather than having to apply additional ceremony to achieve the desired functionality.

3. Lexical ‘this’: Eliminating the Need for ‘bind()’ or ‘var self=this’

This is perhaps the most significant semantic differences between arrow functions and traditional functions. Traditional functions contain a variable named “this” whose value is determined based upon how the function was invoked. Arrow functions however do not provide this capability. The “this” value provided by an arrow function comes from the surrounding scope (lexically scoped) and cannot be altered.

While this may seem complex, it will have a substantial effect on your coding practices. In traditional event handling, callback functions, and object methods you likely had to employ some sort of workaround (such as var self=this or function(){}.bind(this)) in order to ensure that the correct “outer this” was preserved. Arrow functions remove the need for such workarounds.

As an example, if you have a class method that employs setTimeout, a traditional function employed within it will lose its reference to the class instance via this. An arrow function employed in this method will capture this from the outer method allowing direct access to the class property.

Likewise, in event handlers, an arrow function will employ the this from its parent scope (not necessarily the element receiving the event). While this can be desirable and undesirable simultaneously depending on your requirements, you should be deliberate in employing an arrow function here.

Due to arrow functions not possessing their own “this”, they can never be employed as a constructor using new. Additionally, because arrow functions do not possess their own arguments object, although rest parameters may be utilized as an alternative.

4. When Not To Utilize Arrow Functions

Despite their various advantages, arrow functions are not always suitable. Recognizing when they may be unsuitable is equally as vital as recognizing when they are advantageous.

Do not utilize arrow functions in object methods that require their own “this”. For example, if you have an object with a method that accesses this.property, a traditional function will operate off of the object itself whereas an arrow function will operate off of the outer scope (most commonly either the window or the enclosing function’s “this”) potentially resulting in errors.

Do not utilize arrow functions as constructors. They lack the internal [[Construct]] method required to construct instances with new therefore attempting to call an arrow function using new results in an error. Employ traditional functions for construction-based functionality or for classes/constructor-based functionality.

Be cautious when utilizing arrow functions as event handlers. Arrow functions will not operate off of this referencing the element which received the event. Instead, employ traditional functions in those cases where you desire this to reference the event target.

Employ parentheses around objects being returned implicitly from arrow functions. () => ({key:value}) not () => {key:value}.

Switch to traditional functions whenever you require access to the arguments object. Alternatively consider using rest parameters.

Finally, avoid employing arrow functions in scenarios where you require dynamically defined this-contexts such as in DOM event handlers where you wish this to reference the event-target. In those cases employ traditional functions.

5. Arrow Functions in Callbacks and Functional Programming

Arrow Functions truly thrive in callbacks and functional programming scenarios. Methods including map(), filter(), reduce(), foreach(), setTimeout(), and promise-chains can all benefit from increased readability due to utilization of arrow-functions.

Consider a generic pipeline of transforming data. Perhaps you have an array of numbers and want to filter out even values, multiply odd values by two and calculate a total. With arrow-functions each operation appears as a separate logical operation and collectively read like a sequence of actions taken against your original array. Every action is performed by a small, focused arrow-function.

Arrow Functions also pair well with newer asynchronous paradigms. Promise-chains can be written using .then(response => response.json()); instead of .then(function(response){return response.json();});. Async/Await does not utilize arrow-functions nearly as frequently but still provides alternatives for callbacks passed to utility-methods.

The combination of implicit-returns along with lexical-this provides ideal pairing for callbacks that need access to outer-scoped variables without needing further binding.

Conclusion

Understanding these five fundamental concepts (arrow-functions syntax, implicit-return, lexical-this, knowing when to avoid them and utilizing them in callbacks) will give you a thorough understanding of JavaScript’s arrow-functions.

Begin by replacing simple-callbacks with arrow-functions. Observe how much cleaner your code appears. Next try experimenting with object-methods to identify when utilizing an arrow-function will cause complications. Familiarize yourself with identifying situations where traditional functions are superior.

Your objective is not merely to convert all of your traditional functions into arrows. Rather, it is to develop proficiency in both and determine which one best fits each particular situation.

Reference Checklist for Mastering JavaScript Arrow Functions

  • Below is a quick-reference list intended to assist you in developing expertise with JavaScript’s arrow-functions.
  • Use arrow-functions for small-simple callbacks. They minimize visual-clutter and promote improved readability.
  • Utilize implicit-return when you have single-expressions. Omit curly-brackets and return-keyword.
  • Keep in mind that arrow-functions employ lexical-this. Therefore, arrow-functions inherit this from their parent-scope and do not require bind() or var self=this.
  • Avoid utilizing arrow-functions in object-methods that require their own this.
  • Avoid utilizing arrow-functions as constructors. They cannot be called with new.
  • Proceed with caution regarding event-handlers. Arrow-functions do not inherit the element as this. Consider utilizing a traditional-function if you require this to reference the event-target.
  • Use parentheses around objects being returned from implicit-arrow-functions. () => ({key:value}) not () => {key:value}.
  • Transition back to traditional functions whenever you require access to the arguments-object. Alternatively utilize rest-parameters.
  • Lastly, avoid utilizing arrow-functions in scenarios where you require dynamically defined this-contexts such as DOM-event-handlers where you wish this to reference the event-target.

For deeper dives into these topics, the MDN Arrow Functions Guide has comprehensive documentation with examples. Another excellent resource is JavaScript.info’s section on arrow functions, which offers clear, practical explanations for beginners.

New to HTML? Start Here: HTML Tutorial for Beginners: Your Complete Introduction to HTML Basics
New to CSS? Start Here: CSS Introduction: Master 5 Core Concepts Easily
New to JavaScript? JavaScript Introduction: 5 Proven Steps to Learn JS

[INSERT_ELEMENTOR id=”122″]

Leave a Comment

Your email address will not be published. Required fields are marked *

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.