Skip to main content

Javascript: Arrow Functions

Hi techies! This blog is the continuation of the 2-part series discussing about Event Loops and Arrow functions. I hope you have already read about Event Loop and have an understanding about it. Let’s continue with this blog the discussion about Arrow Functions.

Brief Introduction
Arrow functions are like regular functions with a shorthand (=>) notation. There are a few key differences between both of them like binding of “this” construct, syntactical differences and absence of prototype property to name a few.

Arrow functions were introduced in ES6 (or ECMA 2015). ECMAScript (or ES for short) is a standard for scripting languages like JavaScript, Jscript, etc.

Why should I care?
  • Context binding - Arrow syntax automatically binds “this” to the surrounding code’s context. This is useful in some scenarios where if use a regular function notation, then we would get unexpected results.

    Let’s say we own an ice-cream parlor and we store ice-creams information in below fashion-



    Why did we get “undefined” in the getOffers method? Because in a regular function, “this“ construct is binded to the object that invokes that function. Since setTimeout is a part of browser APIs, this refers to Timeout API and not to our “iceCream” object and hence we get undefined result.

    Before ES6, there were some mechanisms through which we could bind “this” to the current context. Like as below-


    Using arrow functions makes it easier to solve this problem.


    This gives the expected result because “this” in arrow functions refers to the lexical scope, i.e., where the arrow function was defined and not who invoked it.

  • Less verbose- The syntax allows an implicit return when there is no body block, resulting in shorter and simpler code in some cases. Check for examples in following section.
Examples:

Case I: No arguments/More than one argument with single statement in the body.

Let’s say a customer arrives at our Ice Cream Parlor. We greet him like below.


Next, we take his order and verify if the ordered Ice Cream is available in our parlor or not.


Here, we see with a single body statement, return keyword is implicit.

Case II: One argument with multiple statements in the body.

Let’s say customer has initiated a payment for his order and we’ll check whether payment succeeds or not.


Here we have omitted parenthesis enclosing the argument.

Limitations
  • Defining methods on an object - Arrow functions cannot access object properties using “this” construct inside a method declared in the object because the arrow function binds the context lexically with the window object. Ex.


    We should instead use regular functions to define methods and access properties.


  • Using constructors - Arrow functions cannot be used as constructors. When we use “new” keyword to instantiate a function, it will create a new object and bind “this” with the object. But since arrow functions binds “this” with the enclosing context, it doesn’t make sense to use “new” keyword with them. JavaScript implicitly prevents from doing that by throwing an exception. Ex.


  • No arguments object – Arrow functions don’t have “arguments” object unlike regular function expressions. Ex.


    This will throw an error. We should use rest parameters here.


Regular functions v/s Arrow functions

 

Differences

Regular functions

Arrow functions

1.

Duplicate parameters

Can have duplicate named parameters in non-strict mode

Cannot have duplicate named parameters in both strict and non-strict mode

2.

“this” binding

They have their own “this” binding. Value of “this” depends on how function is invoked

The value of “this” inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of “this” in the closest non-arrow parent function.

3.

“arguments” object

Inside the body of a regular function, “arguments” is a special array-like object containing the list of arguments with which the function has been invoked.

No “arguments” object is defined inside an arrow function.

 

The “arguments” object is resolved lexically: the arrow function accesses arguments from the closest outer non-arrow function.

4.

“new” keyword

Regular functions created using function declarations or expressions are constructible (means that we can use regular functions as constructors) and callable. And since regular functions are constructible, they can be called using the “new” keyword.

The arrow functions are only callable and not constructible, i.e. arrow functions can never be used as constructor functions. Hence, they can never be called with the “new” keyword.



We have completed the 2-post series discussing what is an event loop, why should we care, and we have seen an example step by step on how it will be executed via event loop in the first post. In the second post we talked about what are arrow functions, why should we care, and some examples to illustrate their use. We have also seen what are its limitations and differences between arrow and regular functions. Understanding these topics can immensely help a developer with better understanding of JavaScript and in writing more efficient and cleaner code.

References

About Amlgo Labs : Amlgo Labs is an advanced data analytics and decision sciences company based out in Gurgaon and Bangalore, India. We help our clients in different areas of data solutions includes design/development of end to end solutions (Cloud, Big Data, UI/UX, Data Engineering, Advanced Analytics and Data Sciences) with a focus on improving businesses and providing insights to make intelligent data-driven decisions across verticals. We have another vertical of business that we call - Financial Regulatory Reporting for (MASAPRAHKMAEBAFEDRBI etc) all major regulators in the world and our team is specialized in commonly used regulatory tools across the globe (AxiomSL Controller ViewOneSumX DevelopmentMoody’s RiskIBM Open Pages etc).We build innovative concepts and then solutions to give an extra edge to the business outcomes and help to visualize and execute effective decision strategies. We are among top 10 Data Analytics Start-ups in India, 2019 and 2020.

Please feel free to comment or share your views and thoughts. You can always reach out to us by sending an email at info@amlgolabs.com
 or filling a contact form at the end of the page.

Comments

More Popular Posts

JavaScript: The Important Basics

In this weird world of technology people often get confused how does a website work? What all things should I be aware of? So we are here to help you. Most of the content on web is developed with the help of JavaScript. JavaScript is really becoming popular these days with the coming of ECMAScript2015 and ECMAScript 2016, for this reason, some beginners learning React and Angular and are also trying to tackle more modern JavaScript syntax at the same time. If you're new to both, it can be confusing as to "what is JavaScript and what are its important features". This document should serve as a primer to help you get up-to-speed on JavaScript syntax that we feel matters the most for learning React as well as Angular.

Amlgo Blog - Experience The Experiments

Amlgo Labs Blog  is a step towards our vision to share knowledge and experiences, Amlgoites accept every challenge very enthusiastically. We do experiments, we fail but we learn and build complex solutions to help our clients solve their problems in Data, Analytics, Prediction, Forecasting, Reporting, Designing and Development area. During this process we enjoy immense learning everyday and we have decided to share our thoughts, learnings, experiments and experiences so that we don't work in silos and contribute the best of our knowledge towards community and learn more by views and reviews. This website is maintained and brough to you by  Amlgo Labs Professionals .   Our Strong Basics -  1)   KISS (Keep It Simple and Straightforward) :  We believe most of the problems can be solved by keeping things simple and straight. This is the learning we had in past, sometimes we try to solve technical problems using high end algorithms and complex codes but this results into complications.

Power BI Blog - What is Power BI and Why we use Power BI.

This Power BI blog is an introduction to the Power BI. In this Power BI tutorial, you will learn Power BI basics - what is Power BI, Power BI Desktop and Power BI Service. Power BI tool is a combination of Business Intelligence and Visualization. Before we dig deep let’s understand what is Business Intelligence. Business Intelligence is a broad spectrum which consists of using different business strategies and techniques to gather data, refine it and process it for the purpose of data analysis which gives us some meaningful information which helps in data driven decision making. When we present this information in the form of some charts, graphs it takes the form of Visualization.

Polybase Blog - Introduction

Overview: This Polybase blog series is all about the use of Polybase Technology in today’s era to be able to take advantage of the Data(Relational and Non-Relational) by using T-SQL only. Data whether Big or not is the lifeline to many different sectors to cope up with Production, Maintenance, Predictions, Taking Precautionary Measures, Customer Satisfaction, Customer Retention, Sales, Revenue Generation and many more.

Polybase Installation for Scale-Out process

This part is the continuation of the previous blog about the introduction of  Polybase Scale-Out Group . As we have discussed in our earlier blog PolyBase enables your SQL Server instance to process Transact-SQL queries that read data from external data sources. SQL Server 2016 and higher can access external data in Hadoop and Azure Blob Storage. Starting in SQL Server 2019, PolyBase can be used to access external data in SQL Server, Oracle, Teradata, and MongoDB.

Stages of New Regulatory Reporting Implementation

In the last blog, we discussed what is  Financial Regulatory Reporting  and its importance in the banking industry. Regulatory Reporting comprises the submission of business numbers as required by regulators to evaluate and track the financial and operational status of financial institutions and their compliance with required regulatory provisions.

A simplified view of a QlikView tool:

In our last blog related to Qlikview, we discussed the use of Qlikview for Financial Data Analytics . Qlikview is a Business Intelligence tool that consists of a front end to visualize the processed data and a back end to provide the security and publication of the mechanism for QlikView user documents.