Arrow function (also known as “fat arrow; =>
” function) was introduced in ECMAScript 2015 as a new syntax for declaring functions.
Two main differences between an arrow function and a regular function are:
1.Basic Syntaxes:
Arrow functions provide a more concise syntax for writing function expressions. They allow us to have implicit returns with a shorter syntax by removing curly brackets {}
and return
keyword. The details will be explained in this article with examples.
2. The Way **this**
Binds:
Arrow functions do not have their own bindings to this
, unlike regular functions. They have lexically bound this
meaning that the value of their this
is determined by the scope that they are in. The behavior of this
keyword is not the focus of today’s article, it will be explained in another post.
Arrow functions introduce a shorter function syntax than regular functions, let’s take a look at the following code examples to understand the difference.
Here is how we declare a function:
The same function can also be written like the following by storing it in a variable to call later with that name:
We will need to declare arrow functions as variables because they are anonymous functions means that they are not named.
Now, let’s convert the above function into an arrow function:
As you see in the example, the function
keyword is dropped and fat arrow(=>
) comes after the parameter ; (color)
, and before the curly brackets {}
.
#web-development #javascript #arrow-functions #es6 #programming