Arrow Function in JavaScript

ยท

2 min read

The arrow function is introduced in ES6 which is a more straightforward form of the traditional function we used. While both functions work in the same manner.
Example of arrow function:

const arrowFunction = () => 'This is Arrow Function';
arrowFunction();
// Output: 'This is Arrow Function'

Below is an example of what it would look like in traditional function:

function traditonalfunction() {
    console.log('This is Traditional Function')
}
traditonalfunction();
// output: This is Traditional Function

In the above example, you can see that we don't have any parameters still we have to write in multiple lines. The arrow function made it simpler with just a one-liner.

The arrow function returns value implicitly, in the case when the function has only one statement so we don't have to use the return keyword.

so now you will be thinking what if a function has a multi-liner?

Let's check it out:

const greater = (a,b) => {
    if(a>b)
        { 
            return true;
        }
}
greater(5,4)
// output true

For multi-liner, we have to use the {} and explicitly use the return keyword to return the value.

you can also skip the parenthesis if there is only one parameter.

const greet = name => console.log('Hello',name);
//output Hello Naruto

Now let's see what happens when we don't explicitly give a return keyword ๐Ÿค”

const hello = () => {'hello'}
hello()
//output: undefined

We can see output will be undefined it is because we have used a block body and not returned a value.

Hope you like it and also learned. I will be adding more concepts as I learn more.
Feel free to correct me and give me feedback.๐Ÿ˜‡

ย