As I Understand — Arrow Functions
What is an arrow function?
Arrow functions are not just a “shorthand” for writing small stuff. Apart from being just a “shorthand” for writing small stuff but also have some very specific and useful features.
To begin with, let’s see how we can write our good old hello world program with the help of arrow functions.
Looks Impressive, Arrow functions allows us to have an implicit return:
we can return values without having return keyword.
When we work with expression bodies (single-line functions) this works.
Let us have a look at the syntax for arrow functions?
We can discuss 3 cases while we write an arrow function:
- No parameters: Empty parentheses followed by => and then expression body or statement body.
- Single parameter: We can omit the parentheses around the parameter.
- Multiple parameters: Enclose the parameters into the parentheses followed by => then expression body or statement body.
So far sounds good. Do we have any other benefit to use the arrow functions? Yes, apart from the concise syntax, another benefit is the lexical binding of this keyword. It means that it uses this from the code that contains the arrow function. Before arrow functions, every new function defined its own this.
Depending on how the function was called the value of this differed.
- A new object in the case of a constructor.
undefinedin strict mode function calls.- The base object if the function was called as an “object method”.
Let's look at an example to understand.
.bind(this) is required to help pass this context into the function. Otherwise, by default, this would be undefined.
arrow functions can’t be bound to thiskeyword, so it will lexically go up a scope, and use the value of this in the scope in which it was defined.
This article discussed the two main benefits of arrow functions:
- Shorter Syntax
- No binding of
this
