Arrow functions are a concise way to write functions in JavaScript. They provide a shorter syntax compared to traditional function expressions.
The syntax for defining an arrow function is as follows:
Or even shorter if the function contains and returns single expression.
This arrow function code is the same as:
Output:
This arrow function code is the same as:
Output:
Inside arrow function this points to the parent scope.
Let's look at the following example:
Output:
Both arrow and traditional function use this. This inside arrow function points to the parent which doesn't have properties
firstName
and lastName
. That's why undefined is printed for their values.
This inside a traditional function points to the current scope. That's why the object's properties values - Alex
and Joe
are printed since this points to the object scope.
Another way to understand it is via the following example:
Output:
The this keyword inside the function presentTraditional
points
to the current scope so it has the values 'Smith'
and 'James'
for the properties firstName
and lastName
.
The this keyword inside the function presentArrow
points
to it's parent scope so it has the values 'Alex'
and 'Joe'
for the properties firstName
and lastName
.
If at line 4
we change the function declarations from traditional to arrow, then the
presentArrow
function would have undefined values for the properties firstName and lastName since this would point to the global scope inside the function printGreetings
.