One of the most popular features introduced in ES6 is the arrow function (also known as fat arrow function). It’s a concise way of defining function.
Consider the following example:
But that’s not the only reason why arrow functions are so popular.
Let’s first understand what the this pointer uncertainty is. Have a look at the code below:
What happened here?
jsObject in our case).
So, when our code looked for a variable named message in
jsObject, it couldn’t find it. Let’s fix the code and add the
message variable in our object.
Note the variable assignment in the object.
When we assigned a value to the internal message variable of
jsObject, the this pointer was still pointing to the global object.
But earlier, when the same this pointer was used inside the function, it was pointing somewhere else, i.e. to our
Now, in a large application, it gets hard to keep track of the this pointer and the passing of the required value to the appropriate function. This is where the arrow function syntax comes in.
If you are accessing the this pointer in your function and you want it to point to the surrounding code of the function definition, use the arrow syntax.
printMessage using the arrow syntax and see what happens.
Also, change the value of the internal
message variable, so we know where the this pointer is pointing when we call the functions.
So that’s how the fat arrow function resolved the this pointer uncertainty issue.
Don’t assume, while using the arrow function, that the this pointer will always point to the global object.
It’s important to note that, when you’re defining functions using arrow functions, wherever the this pointer will point to totally depends on the surrounding code of the function definition.
Thank you for reading!