What are Arrow Functions?
I have previously talked about arrow functions in my other post.
Basically, arrow functions introduced in es6 are writing normal functions but in a more concise and shorter way.
Arrow functions are by default anonymous, you have to assign the function to a variable to access it.
Implicit return:
Using arrow function we can return something implicitly ie.. without actually using the keyword return
const sayHi = (name) => `Hi ${name}`;
sayHi('bruce');
//result
Hi bruce
See? the string is being returned without using the keyword return
, well it's not a big thing but keeps the code clean.
Note: Since, arrow functions are assigned to a variable, these aren't hoisted.
Things you must know about Arrow function😆
Arrow functions do not bind their own this, instead, they inherit the one from the parent scope, which is called
lexical scoping
. This makes arrow functions to be a great choice in some scenarios but a very bad one in others.
ie..this
inside the arrow function would have the same value as it did right before the arrow function was assigned.An arrow function expression has a shorter syntax compared to function expressions and lexically binds the
this
value (does not bind its ownthis
,arguments
,super
, ornew
).Arrow functions are always anonymous. This means you cannot bind a value to
this
.So, in a case where you want to make use of closures and utilize the power of
this
keyword then arrow functions are not a great choice and will break your code.
Here we talked about lexical scoping
, this
keyword and binding
, if you have no idea what those mean, we will discuss those concepts at the end of this series. ☺️
WRAPPING UP
Now you know what arrow functions are, how and when to use them along with a concept called implicit returns to make your code look cleaner.
Stay tuned for further posts in this series. 😁
Thank you!
Top comments (0)