Skip to main content

Things Everyone Knows About Javascript Arrow Functions But You Don’t

Javascript arrow functions in modern JavaScript is one of the most powerful features of the ES6+. After ES6+ update, arrow function completely changes the way you write the javascript code. They introduce a new way of writing concise and clean code. They save developers lots of time and simplify the function scope.

In this article, we are going to learn all the details of Javascript arrow function like how to use arrow function, the syntax of them, this keyword scope in js arrow function, use case of the arrow function in Javascript.

What is Arrow Function in JavaScript?

Arrow functions in javascript is a more concise syntax of writing the JavaScript functions. They also are known as a fat arrow function. They first introduce in the ES6/ ECMAScript 2015.

Arrow function in Javascript works much like the Lamba function of the Python. Values in the JS arrow function are returned without having the use of return keyword. It allows you to have an implicit return.

Javascript Arrow Functions Syntax

There are variety of syntaxes available for the arrow function. MDN has a full list of them. Here we will cover the most common used syntaxes from them one by one. Here I will show you both es5 and es6 version so that you can understand more clearly what is the changes in the ES6 arrow function syntax. Below are the details of them

One Parameter

//ES5
var splitStringES5 = function splitString(string) {
  return string.split(' ');
};

//ES6
const splitStringES6 = string => string.split(" ");

Multiple Parameter

// ES5
var addNumbersES5 = function(a, b) {
  return a + b;
};

// ES6
const addNumbersES6 = (a, b) => { return a * b };

Syntax with No Parameter

//ES5
var noParamEs5 = function noParamEs5() {
    console.log("I am ES5 function");
};

//ES6
let noParamEs6 = () => { console.log("I am ES6 function"); };

Example of Arrow function

Till now, we cover the basic syntaxes, now let’s see them into real-life examples. When and how to use the arrow functions in Javascript?

One of the most common use cases of this is in the array manipulation. Suppose you have an array which contains the list of employees and you want the get their names only then you can do that by using arrow function like below

const employees = [
    {
         "name" : "joe",
         "salary" : 12000
    },
    {
         "name" : "sam",
         "salary" : 15000
    },
    {
         "name" : "jerry",
         "salary" : 13000
    },
    {
         "name" : "tom",
         "salary" : 12000
    }
];

// ES5
var salariesES5 = employees.map(function(employee) {
  return employee.salary;
});

// ES6
const salariesES6 = employees.map(employee => employee.price);

Above code is very simple to understand. Here, we first declare the employee variable and then extract the price of all the employees using both ES5 and ES6. We also use the javascript map function which is one of the most used functions in the modern javascript.

Another example of this is using the javascript filter method to get even numbers from the array. We can get the even numbers from the array of numbers easily in only one line of code like below

const numbers = [1,2,3,4,5,6,7,8,9];

const evenNumbers = numbers.filter(number => number %2 === 0);

console.log(evenNumbers);

//output [2,4,6,8]

How this Keyword works in JS Arrow Function

I bet everyone at their beginning have confusions with this keyword. It is a very complicated concept to grasp at the beginning of every developer.

Arrow functions behave totally different from the regular JavaScript functions. So it is very important to highlight this into this article.

Read all the lines below this very carefully because this is the main difference between Javascript arrow functions and regular functions.

Let’s understand this keyword in Javascript arrow function by an example.

//ES5
const person = {
  fisrtName: 'John',
  lastName: 'Doe',
  fullName: function() {
    return `${this.fisrtName} ${this.lastName}`
  }
}

Now if in the above code you call person.fullName then you will get John Doe in return. In the above code, fullName is a regular function and in regular function, this refers to the object but this is not the case with the arrow functions of the Javascript.

Let’s rewrite above code into ES6 with arrow functions.

//ES6
const person = {
  fisrtName: 'John',
  lastName: 'Doe',
  fullName: () => {
    return `${this.fisrtName} ${this.lastName}`
  }
}

Now if you can the fullName in the above code then you will get undefined.

Something More About JavaScript Arrow Functions

Let’s know a little bit more about the arrow functions like where we can use this and where we can’t use it. Below is some list where you can’t use it.

  • Arrow functions can’t be used as a constructor. If you use new with arrow functions then will throw an error message.
  • You can’t use this as a generator because they are designed to be lightweight. Using the yield keyword will throw an error.
  • An empty arrow function returns undefined.
  • An arrow function cannot contain a line break between its parameters and its arrow.
  • They do not have a prototype property.
  • They don’t have their own arguments object. Use rest operatorsinstead of the arguments object.
var arguments = [1, 2, 3];
let arr = () => arguments[0];

arr(); // 1

function foo(n) {
  var f = () => arguments[0] + n;
  return f();
}

foo(3); // 6

Conclusion

Javascript arrow functions have been called one of the most popular features of the ES6+. They become the default function for the modern javascript code unless the function expressions or declarations are necessary.

They are here and concise, simple, powerful and most of the developers love it and you should start using it if you are not started yet.

Before going to use it into your code, I will suggest you test its compatibility with all the browser so in future you don’t face any difficulties.

IF you have any doubts and suggestions then please comment in the comment box and I will reply as soon as possible.


Comments

Popular posts from this blog

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...