What is arrow function in javascript?

By : Admin  |  Updated On : 1 day ago

What is arrow function in javascript?

Introduction to ES6 javascript arrow function.

ES6 provides a shorter way to write arrow function as compared to normal anonymous function. The function which doesn't have a name and created at runtime is anonymous function while arrow function is also anonymous function with some special features. 

Features :

1. Arrow function shortened the syntax as compared to regular function.

//Regular Function
getData = function() {
  return "Hello World!";
}

//Arrow Function
getData = () => {
  return "Hello World!";
}

 

2. If single line expression is there in arrow function then no need to put return statement it automatically return, where in normal anonymous function has to  mention return statement.

//Regular Function
getData = function() {
  return "Hello World!";
}

//Arrow Function (Dont put curly braces if single line statement)
getData = () => "Hello World!";

 

3. Parenthesis () is optional when there is only one parameter. Parenthesis are required when no parameter. 

//Parenthesis is optional when only 1 parameter.
getData = param1 => return "Hello World!";

//Parenthesis required when no parameter.
getData = () => " Hello World!";


4. Arrow function doesn't have its own this object it always represent this object who defined it. Where as normal functions, this keyword represented the object that called the function like example below:

Ex : Regular function always represent this object who calls the function.

//Regular Function:
getData = function() {
  document.getElementById("demo").innerHTML += this;
}

//The window object calls the function:
window.addEventListener("load", getData);
//output : [object Window]

//A button object calls the function:
document.getElementById("btn").addEventListener("click", getData);
//output : [object HTMLButtonElement]

Ex :  Arrow function represent this object of owner of the arrow function.

//Arrow Function:
getData = () => {
  document.getElementById("demo").innerHTML += this;
}

//The window object calls the function:
window.addEventListener("load", getData);
//output : [object Window]

//A button object calls the function:
document.getElementById("btn").addEventListener("click", getData);
//output : [object Window]