Love at first sight! Who doesn’t love the simplicity of them? Introduced as part of the ECMAScript 6, arrow functions went viral, and we all know why. The new syntax to declare functions is wonderful, saving us time and enhancing clarity in many situations, removing all the distracting, unnecessary, chunk that usually came with declaring a JS function.
Let’s take an example of a regular function declaration, and the same function using arrow functions:
function welcome() {
return "Welcome!"
}
And with ES6 Arrow Functions
const welcome = () => "Welcome!"
Not evident enough? Let’s look at another example:
const f = list.map(function(item) { return item; })
vs
const f = list.map((item) => item)
Ain’t that beautiful?
However, we need to be careful, as the differences between the 2 declarations are not just syntax, and thus it cannot be applied in every situation. Let’s now take a look at situations under which using Arrow Functions is not the right way.
Take a look at the following example:
const article = {
claps: 0,
clap: () => {
this.claps++;
}
}
In this example, it would be intuitive to think that every time we call article.clap()
the attribute article.claps
would increase by one, initially from 0 to 1. However, this is not the case, the value of claps will sadly remain the same and this article will never get to be popular.
Since this author doesn’t like that idea, let’s see why this doesn’t work. The problem, as usual, is with this
and scoping.
#javascript #react #typescript #programming