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

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...