Arrow functions were introduced in es6 or es2015, since then it's very popular among developers. And it's the coolest thing that I love the most.
Arrow functions changed the way we declare a function. It's made functions declaration easy, fast and stylish.
The arrow in it's name come from it's arrow like syntax. Let's take an example
const foo = () => console.log('Hey, Arrow!');
How to use it
Arrow functions works very similar to anonymous functions.
//Anonymous functions
const foo = function () {
console.log("I'm old!");
}
//Arrow functions
const foo = () => {
console.log("I'm new!");
}
But arrow functions provide more flexibility.
Like if you have only one statement in function body then you can remove those curly braces.
const foo = () => console.log("Isn't it cool!");
Also if you returning some value you don't need to provide the return kayword.
const foo = () => "Wow!"
And if you need to return an object you would do.
const msg = () => ({
type: 'msg',
body: 'Hey'
})
Now, You can pass multiple parameters to it.
const add = (a, b) => a + b;
And last but not the least, if you have only one parameter you also can remove those Parenthesis.
const product = a => a * a;
Now look how easy it is to declare a function using arrow functions.
I hope you learn something from this article. Thanks for reading..
Top comments (0)