DEV Community

Soumak Dutta
Soumak Dutta

Posted on • Edited on

Understanding Arrow functions in JavaScript

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!');
Enter fullscreen mode Exit fullscreen mode

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!");
}
Enter fullscreen mode Exit fullscreen mode

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!");
Enter fullscreen mode Exit fullscreen mode

Also if you returning some value you don't need to provide the return kayword.

const foo = () => "Wow!"
Enter fullscreen mode Exit fullscreen mode

And if you need to return an object you would do.

const msg = () => ({
    type: 'msg',
    body: 'Hey'
})
Enter fullscreen mode Exit fullscreen mode

Now, You can pass multiple parameters to it.

const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

And last but not the least, if you have only one parameter you also can remove those Parenthesis.

const product = a => a * a;
Enter fullscreen mode Exit fullscreen mode

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)