loading

ES6 Arrow Functions

Arrow Functions

Arrow functions enable us to write shorter function syntax.

Example

Before:

				
					hello = function() {
  return "Hello World!";
}
				
			

Example

With Arrow Function:

				
					hello = () => {
  return "Hello World!";
}
				
			

It becomes shorter! If the function just contains one statement and that statement returns a value, you can eliminate the braces and the return keyword.

Example

Arrow Functions Return Value by Default:

				
					hello = () => "Hello World!";
				
			

This only works if the function has a single statement.

If you have parameters, you pass them inside parentheses.

Example

Arrow Function With Parameters:

				
					hello = (val) => "Hello " + val;
				
			

In fact, if you only have one argument, you can also skip the parenthesis.

Example

Arrow Function Without Parentheses:

				
					hello = val => "Hello " + val;
				
			

What About this?

The processing of this differs between arrow functions and normal functions.

In brief, arrow functions do not bind this.

In ordinary functions, this keyword denoted the object that invoked the function, which may be a window, a document, a button, or whatever.

With arrow functions, the this keyword always refers to the object that defines the arrow function.

Let’s look at two cases to see the difference.

Both instances call a function twice: once when the website loads, and again when the user clicks a button.

The first example utilizes a standard function, while the second employs an arrow function.

The result demonstrates that the first example returns two separate objects (window and button).

Example

With a regular function, this represents the object that called the function:

				
					class Header {
  constructor() {
    this.color = "Red";
  }

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

const myheader = new Header();

//The window object calls the function:
window.addEventListener("load", myheader.changeColor);

//A button object calls the function:
document.getElementById("btn").addEventListener("click", myheader.changeColor);
				
			

Example

With an arrow function, this represents the Header object no matter who called the function:

				
					class Header {
  constructor() {
    this.color = "Red";
  }

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

const myheader = new Header();


//The window object calls the function:
window.addEventListener("load", myheader.changeColor);

//A button object calls the function:
document.getElementById("btn").addEventListener("click", myheader.changeColor);
				
			

Remember these distinctions while working with functions. Sometimes the behavior of regular functions is desirable; otherwise, utilize arrow functions.

Share this Doc

ES6 Arrow Functions

Or copy link

Explore Topic