JavaScript Arrow Function


Arrow functions were introduced in ES6.

Arrow functions allow us to write shorter function syntax:

let myFunction = (a, b) => a * b;

It becomes shorter! If the function has just one statement and that statement gives back a value, you can leave out the brackets and the return word:

Note: This only works if the function contains just one statement.

If you possess certain values, you insert them within the brackets:

Certainly! If you have only one parameter, you can skip using parentheses, like this:


What About this?

Arrow functions handle this differently than regular functions do.

Simply put, arrow functions don't bind the this keyword.

In typical functions, the this keyword stands for the object that triggered the function, such as the window, the document, a button, or anything else.

Arrow functions ensure that the this keyword always points to the object that made the arrow function.

Let's explore two examples to grasp the distinction.

Both instances execute a function two times: initially upon the page's loading and then once more when the user clicks a button.

The initial instance employs a standard function, while the second instance utilizes an arrow function.

The outcome indicates that in the first example, two distinct items are obtained (window and button). In the second example, the window object is retrieved twice because it serves as the "owner" of the function.

Keep in mind these distinctions when dealing with functions. If the typical function's behavior suits your needs, stick with it; otherwise, opt for arrow functions.